aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-model/src/main/java
diff options
context:
space:
mode:
authorvasraz <vasyl.razinkov@est.tech>2021-03-19 12:07:04 +0000
committerChristophe Closset <christophe.closset@intl.att.com>2021-03-19 16:59:55 +0000
commit260a951d3431429bab9732e16225e42641ae4787 (patch)
treeecd7b86def3c5f3ce267d7d1c9ce6634a893a293 /catalog-model/src/main/java
parentdbcffb741906842005a53b6c8d76395179833943 (diff)
Reformat catalog-model
Signed-off-by: Vasyl Razinkov <vasyl.razinkov@est.tech> Issue-ID: SDC-3449 Change-Id: I8dca05304f656894cfb70329c45d8cd5d1ca925c
Diffstat (limited to 'catalog-model/src/main/java')
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java14
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java20
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/AnnotationTypeDefinition.java30
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java45
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactType.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactUiDownloadData.java23
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/CapReqDef.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java60
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityRequirementRelationship.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityTypeDefinition.java22
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabiltyInstance.java7
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/CatalogUpdateTimestamp.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Category.java21
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Combination.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java48
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentDependency.java20
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java15
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstListInput.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstOutputsMap.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribOutput.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java21
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java21
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInterface.java22
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceOutput.java16
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstancePropInput.java13
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java64
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentMetadataDefinition.java25
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java11
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ConsumerDefinition.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/DataTypeDefinition.java11
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java14
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionTransitionEnum.java14
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/FunctionalMenuInfo.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java134
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java77
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstanceProperty.java7
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java12
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupTypeDefinition.java31
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/HeatParameterDefinition.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeOutputCommon.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/IComplexDefaultValue.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/IComponentInstanceConnectedElement.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/IOperationParameter.java15
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java11
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java15
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/LifeCycleTransitionEnum.java12
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/LifecycleStateEnum.java13
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/MapInterfaceDataDefinition.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/MapInterfaceInstanceDataDefinition.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java26
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/OperationInput.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/OperationInstance.java62
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/OutputDefinition.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ParsedToscaYamlInfo.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Point.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyDefinition.java13
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTargetDTO.java11
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTypeDefinition.java20
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ProductMetadataDefinition.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyConstraint.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java210
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyScope.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipImpl.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipInfo.java34
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipTypeDefinition.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementCapabilityRelDef.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementImplDef.java13
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementInstance.java7
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java85
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ResourceInstanceHeatParameter.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ResourceMetadataDefinition.java7
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Schema.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java26
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ServiceMetadataDefinition.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Tag.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadArtifactInfo.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadCapInfo.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadInfo.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadNodeFilterCapabilitiesInfo.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadNodeFilterInfo.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java13
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadReqInfo.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadResourceInfo.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadServiceInfo.java202
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/User.java94
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationCache.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java180
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/category/CategoryDefinition.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/category/GroupingDefinition.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/category/SubCategoryDefinition.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java59
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/config/ContainerInstanceTypesData.java26
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplate.java34
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java73
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnum.java29
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnum.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java132
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java436
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java685
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ByToscaNameDerivedNodeTypeResolver.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperation.java77
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java37
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java132
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ForwardingPathOperation.java57
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java351
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InstancesOperation.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperation.java40
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeFilterOperation.java119
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java1224
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java315
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperation.java32
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/RequirementOperation.java62
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/SubstitutionFilterOperation.java75
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java627
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaDataOperation.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java622
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java530
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java1626
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java124
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/exception/ToscaOperationException.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java367
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapper.java21
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java558
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/normatives/ToscaTypeMetadata.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java15
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/DerivedFromOperation.java37
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICacheMangerOperation.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java42
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java21
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java20
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java15
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java7
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IHeatParametersOperation.java14
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java29
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java19
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/StorageOperationStatus.java85
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/TypeOperations.java19
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java80
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java351
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperations.java28
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java258
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java122
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java248
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java248
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java43
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java369
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java31
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java23
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java98
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java101
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java179
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java21
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java405
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java335
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java398
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java160
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java95
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java286
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java74
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java34
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java161
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java4067
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperation.java334
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java50
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java76
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java24
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java106
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java304
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/VersionUtil.java40
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractComparablePropertyConstraint.java16
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractPropertyConstraint.java20
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractStringPropertyConstraint.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java28
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintUtil.java108
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java56
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java33
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java25
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java20
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java58
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintFunctionalException.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintRequiredParameterException.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintTechnicalException.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintValueDoNotMatchPropertyTypeException.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintViolationException.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/FunctionalException.java11
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/InvalidPropertyConstraintImplementationException.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/PropertyConstraintException.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/TechnicalException.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverter.java16
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java27
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverter.java15
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverter.java16
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java22
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java16
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverter.java19
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java164
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverter.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java191
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/PropertyValueConverter.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertor.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverter.java21
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverter.java19
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java53
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java50
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertor.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java69
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueConverter.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverter.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/BooleanValidator.java19
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java155
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/FloatValidator.java19
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatBooleanValidator.java26
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatCommaDelimitedListValidator.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java19
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidator.java41
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/JsonValidator.java16
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java19
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java79
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java82
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java20
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidator.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ApplicationVersionException.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java419
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/Version.java40
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/ComponentUtilities.java28
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/GroupUtils.java86
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/TypeCompareUtils.java162
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/OperationUi.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/PropertyAssignmentUi.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/SerializedHashMap.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UIConstraint.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCombination.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java5
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java29
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiLeftPaletteComponent.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java51
272 files changed, 9990 insertions, 13059 deletions
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java b/catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java
index 061975b1e2..a4d049d597 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.config;
import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
@@ -26,18 +25,19 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
-@ComponentScan({"org.openecomp.sdc.be.model.operations.impl",
+@ComponentScan({
+ // @formatter:off
+ "org.openecomp.sdc.be.model.operations.impl",
"org.openecomp.sdc.be.model.cache",
"org.openecomp.sdc.be.model.jsonjanusgraph.utils",
"org.openecomp.sdc.be.model.jsonjanusgraph.operations",
"org.openecomp.sdc.be.model.jsonjanusgraph.config",
- "org.openecomp.sdc.be.dao.cassandra"
-})
+ "org.openecomp.sdc.be.dao.cassandra"})
+// @formatter:on
public class CatalogModelSpringConfig {
@Bean
public DataTypeValidatorConverter dataTypeValidatorConverter() {
return DataTypeValidatorConverter.getInstance();
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java
index f97b998073..dd2c42f9d0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
+import java.util.List;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
-import java.util.List;
-
public class AdditionalInformationDefinition extends AdditionalInfoParameterDataDefinition {
private String parentUniqueId;
@@ -34,17 +32,19 @@ public class AdditionalInformationDefinition extends AdditionalInfoParameterData
}
public AdditionalInformationDefinition(AdditionalInfoParameterDataDefinition p, String parentUniqueId,
- List<AdditionalInfoParameterInfo> parameters) {
+ List<AdditionalInfoParameterInfo> parameters) {
super(p);
this.parentUniqueId = parentUniqueId;
setParameters(parameters);
}
- public AdditionalInformationDefinition(AdditionalInfoParameterDataDefinition p){
+
+ public AdditionalInformationDefinition(AdditionalInfoParameterDataDefinition p) {
this.setUniqueId(p.getUniqueId());
this.setCreationTime(p.getCreationTime());
this.setModificationTime(p.getModificationTime());
setParameters(p.getParameters());
}
+
public AdditionalInformationDefinition(AdditionalInformationDefinition pd) {
this.setUniqueId(pd.getUniqueId());
this.setCreationTime(pd.getCreationTime());
@@ -60,12 +60,8 @@ public class AdditionalInformationDefinition extends AdditionalInfoParameterData
this.parentUniqueId = parentUniqueId;
}
-
-
@Override
public String toString() {
- return "AdditionalInformationDefinition [ parentUniqueId=" + parentUniqueId + " "
- + super.toString() + "]";
+ return "AdditionalInformationDefinition [ parentUniqueId=" + parentUniqueId + " " + super.toString() + "]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AnnotationTypeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AnnotationTypeDefinition.java
index 63d49e70d4..61e5b412ec 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AnnotationTypeDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AnnotationTypeDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
-import org.openecomp.sdc.be.datatypes.elements.AnnotationTypeDataDefinition;
-import org.openecomp.sdc.be.model.utils.TypeCompareUtils;
-
import java.util.List;
import java.util.Objects;
+import org.openecomp.sdc.be.datatypes.elements.AnnotationTypeDataDefinition;
+import org.openecomp.sdc.be.model.utils.TypeCompareUtils;
public class AnnotationTypeDefinition extends AnnotationTypeDataDefinition {
+ protected List<PropertyDefinition> properties;
public AnnotationTypeDefinition() {
super();
@@ -37,8 +36,6 @@ public class AnnotationTypeDefinition extends AnnotationTypeDataDefinition {
super(annotationTypeDataDefinition);
}
- protected List<PropertyDefinition> properties;
-
public List<PropertyDefinition> getProperties() {
return properties;
}
@@ -48,15 +45,16 @@ public class AnnotationTypeDefinition extends AnnotationTypeDataDefinition {
}
/**
- * This method compares definition properties and ignores products such as
- * actual graph ids that were already assigned
+ * This method compares definition properties and ignores products such as actual graph ids that were already assigned
*/
public boolean isSameDefinition(AnnotationTypeDefinition other) {
- if (this == other) return true;
- if (other == null) return false;
-
- return Objects.equals(type, other.type) &&
- Objects.equals(description, other.description) &&
- TypeCompareUtils.propertiesEquals(properties, other.properties);
+ if (this == other) {
+ return true;
+ }
+ if (other == null) {
+ return false;
+ }
+ return Objects.equals(type, other.type) && Objects.equals(description, other.description) && TypeCompareUtils
+ .propertiesEquals(properties, other.properties);
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java
index 6afce6f138..6a770c03d7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java
@@ -17,16 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
-import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition;
-
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition;
public class ArtifactDefinition extends ArtifactDataDefinition {
@@ -34,17 +32,8 @@ public class ArtifactDefinition extends ArtifactDataDefinition {
* Base64 encoded Artifact file data
*/
private byte[] payloadData;
-
private Boolean isHeatParamUpdated = false;
- public Boolean getHeatParamUpdated() {
- return isHeatParamUpdated;
- }
-
- public void setHeatParamUpdated(Boolean heatParamUpdated) {
- isHeatParamUpdated = heatParamUpdated;
- }
-
public ArtifactDefinition() {
}
@@ -66,12 +55,16 @@ public class ArtifactDefinition extends ArtifactDataDefinition {
setPayloadData(payloadData);
}
- public byte[] getPayloadData() {
- return payloadData;
+ public Boolean getHeatParamUpdated() {
+ return isHeatParamUpdated;
}
- public void setPayload(byte[] payloadData) {
- this.payloadData = payloadData;
+ public void setHeatParamUpdated(Boolean heatParamUpdated) {
+ isHeatParamUpdated = heatParamUpdated;
+ }
+
+ public byte[] getPayloadData() {
+ return payloadData;
}
public void setPayloadData(String payloadData) {
@@ -80,6 +73,10 @@ public class ArtifactDefinition extends ArtifactDataDefinition {
}
}
+ public void setPayload(byte[] payloadData) {
+ this.payloadData = payloadData;
+ }
+
public List<HeatParameterDefinition> getListHeatParameters() {
List<HeatParameterDefinition> res = null;
List<HeatParameterDataDefinition> heatParameters = super.getHeatParameters();
@@ -91,24 +88,20 @@ public class ArtifactDefinition extends ArtifactDataDefinition {
public void setListHeatParameters(List<HeatParameterDefinition> properties) {
List<HeatParameterDataDefinition> res = null;
-
if (properties != null) {
res = properties.stream().map(HeatParameterDataDefinition::new).collect(Collectors.toList());
}
super.setHeatParameters(res);
}
-
-
- public boolean checkEsIdExist() {
- return (getEsId() != null) && (!getEsId().trim().isEmpty());
- }
+ public boolean checkEsIdExist() {
+ return (getEsId() != null) && (!getEsId().trim().isEmpty());
+ }
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
-
result = prime * result + Arrays.hashCode(payloadData);
return result;
}
@@ -125,13 +118,11 @@ public class ArtifactDefinition extends ArtifactDataDefinition {
return false;
}
ArtifactDefinition other = (ArtifactDefinition) obj;
-
if (payloadData == null) {
if (other.payloadData != null) {
return false;
}
- }
- else if (!Arrays.equals(payloadData, other.payloadData)) {
+ } else if (!Arrays.equals(payloadData, other.payloadData)) {
return false;
}
return true;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactType.java
index ec55209ee8..be72d2ffb5 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactType.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactType.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
public class ArtifactType {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactUiDownloadData.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactUiDownloadData.java
index 4fa0536c7a..2b262d22a3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactUiDownloadData.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactUiDownloadData.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
public class ArtifactUiDownloadData {
-
// POJO for UI artifact download, holding artifact filename and base64
+
// content
String artifactName;
String base64Contents;
- public void setArtifactName(String artifactName) {
- this.artifactName = artifactName;
- }
-
- public void setBase64Contents(String base64Contents) {
- this.base64Contents = base64Contents;
- }
-
public String getArtifactName() {
return artifactName;
}
+ public void setArtifactName(String artifactName) {
+ this.artifactName = artifactName;
+ }
+
public String getBase64Contents() {
return base64Contents;
}
+
+ public void setBase64Contents(String base64Contents) {
+ this.base64Contents = base64Contents;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java
index 1cf3baaac7..d1bcedc8ea 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java
@@ -46,13 +46,7 @@ public class AttributeDefinition extends AttributeDataDefinition implements IOpe
@Override
public String toString() {
- return "AttributeDefinition{" +
- "name=" + getName() +
- "uniqueId=" + getUniqueId() +
- "ownerId=" + getOwnerId() +
- "type=" + getType() +
- "description=" + getDescription() +
- "default=" + getDefaultValue() +
- '}';
+ return "AttributeDefinition{" + "name=" + getName() + "uniqueId=" + getUniqueId() + "ownerId=" + getOwnerId() + "type=" + getType()
+ + "description=" + getDescription() + "default=" + getDefaultValue() + '}';
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapReqDef.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapReqDef.java
index bee09fb206..1f618a7c9f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapReqDef.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapReqDef.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import java.util.List;
import java.util.Map;
public class CapReqDef {
+
Map<String, List<CapabilityDefinition>> capabilities;
Map<String, List<RequirementDefinition>> requirements;
@@ -31,8 +31,7 @@ public class CapReqDef {
super();
}
- public CapReqDef(Map<String, List<RequirementDefinition>> requirements,
- Map<String, List<CapabilityDefinition>> capabilities) {
+ public CapReqDef(Map<String, List<RequirementDefinition>> requirements, Map<String, List<CapabilityDefinition>> capabilities) {
super();
this.capabilities = capabilities;
this.requirements = requirements;
@@ -42,14 +41,14 @@ public class CapReqDef {
return capabilities;
}
- public Map<String, List<RequirementDefinition>> getRequirements() {
- return requirements;
- }
-
public void setCapabilities(Map<String, List<CapabilityDefinition>> capabilities) {
this.capabilities = capabilities;
}
+ public Map<String, List<RequirementDefinition>> getRequirements() {
+ return requirements;
+ }
+
public void setRequirements(Map<String, List<RequirementDefinition>> requirements) {
this.requirements = requirements;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java
index 061262eec0..9424c6ff55 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import com.google.common.collect.Lists;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
@@ -28,15 +31,9 @@ import lombok.Setter;
import lombok.ToString;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
-import org.apache.commons.collections.SetUtils;
import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
/**
* Specifies the capabilities that the Node Type exposes.
*/
@@ -48,8 +45,7 @@ import java.util.stream.Collectors;
public class CapabilityDefinition extends CapabilityDataDefinition {
/**
- * The properties field contains all properties defined for
- * CapabilityDefinition
+ * The properties field contains all properties defined for CapabilityDefinition
*/
private List<ComponentInstanceProperty> properties;
@@ -57,41 +53,41 @@ public class CapabilityDefinition extends CapabilityDataDefinition {
super(cap);
}
- public CapabilityDefinition(CapabilityTypeDefinition other, String ownerName, String name, CapabilityDataDefinition.OwnerType ownerType) {
- super(other);
+ public CapabilityDefinition(CapabilityTypeDefinition other, String ownerName, String name, CapabilityDataDefinition.OwnerType ownerType) {
+ super(other);
this.setOwnerName(ownerName);
this.setOwnerType(ownerType);
this.setName(name);
this.setParentName(name);
- if (MapUtils.isNotEmpty(other.getProperties())) {
- this.properties = Lists.newArrayList(other.getProperties().values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()));
- }
- }
+ if (MapUtils.isNotEmpty(other.getProperties())) {
+ this.properties = Lists
+ .newArrayList(other.getProperties().values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()));
+ }
+ }
public CapabilityDefinition(CapabilityDefinition other) {
- super((CapabilityDefinition)other);
-
+ super((CapabilityDefinition) other);
if (other.properties != null) {
- this.properties = new ArrayList<>(other.properties.stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()));
+ this.properties = new ArrayList<>(other.properties.stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()));
}
}
- public void updateCapabilityProperties(CapabilityDefinition capabilityDefinition) {
- if(CollectionUtils.isNotEmpty(getProperties()) && capabilityDefinition!= null && CollectionUtils.isNotEmpty(capabilityDefinition.getProperties())){
- Map<String, ComponentInstanceProperty> propertiesInfo = capabilityDefinition.getProperties()
- .stream()
- .collect(Collectors.toMap(ComponentInstanceProperty::getName, p->p));
- getProperties().forEach(p->p.updateCapabilityProperty(propertiesInfo.get(p.getName())));
- }
- }
+ public void updateCapabilityProperties(CapabilityDefinition capabilityDefinition) {
+ if (CollectionUtils.isNotEmpty(getProperties()) && capabilityDefinition != null && CollectionUtils
+ .isNotEmpty(capabilityDefinition.getProperties())) {
+ Map<String, ComponentInstanceProperty> propertiesInfo = capabilityDefinition.getProperties().stream()
+ .collect(Collectors.toMap(ComponentInstanceProperty::getName, p -> p));
+ getProperties().forEach(p -> p.updateCapabilityProperty(propertiesInfo.get(p.getName())));
+ }
+ }
public void updateEmptyCapabilityOwnerFields(String ownerId, String ownerName, OwnerType ownerType) {
- if (StringUtils.isEmpty(getOwnerId())){
+ if (StringUtils.isEmpty(getOwnerId())) {
setOwnerId(ownerId);
- if(getPath() == null){
+ if (getPath() == null) {
setPath(new ArrayList<>());
}
- if(!getPath().contains(ownerId)){
+ if (!getPath().contains(ownerId)) {
getPath().add(ownerId);
}
setOwnerName(ownerName);
@@ -100,7 +96,7 @@ public class CapabilityDefinition extends CapabilityDataDefinition {
}
private void setOwnerTypeIfEmpty(OwnerType ownerType) {
- if(getOwnerType() == null){
+ if (getOwnerType() == null) {
setOwnerType(ownerType);
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityRequirementRelationship.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityRequirementRelationship.java
index 9eb0357a5c..ae3dadc4d9 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityRequirementRelationship.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityRequirementRelationship.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import java.util.List;
@@ -38,5 +37,4 @@ public class CapabilityRequirementRelationship {
private CapabilityDataDefinition capability;
private RequirementDataDefinition requirement;
private List<OperationUi> operations;
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityTypeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityTypeDefinition.java
index c15d1541d0..b3fb2c4a83 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityTypeDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityTypeDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
+import java.util.Map;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@@ -27,8 +27,6 @@ import lombok.ToString;
import org.openecomp.sdc.be.datatypes.elements.CapabilityTypeDataDefinition;
import org.openecomp.sdc.be.resources.data.CapabilityTypeData;
-import java.util.Map;
-
/**
* Specifies the capabilities that the Node Type exposes.
*/
@@ -40,18 +38,16 @@ import java.util.Map;
public class CapabilityTypeDefinition extends CapabilityTypeDataDefinition {
private String derivedFrom;
-
private Map<String, PropertyDefinition> properties;
public CapabilityTypeDefinition(CapabilityTypeDataDefinition p) {
super(p);
}
- public CapabilityTypeDefinition(CapabilityTypeData ctd) {
- this.setUniqueId(ctd.getUniqueId());
- this.setType(ctd.getCapabilityTypeDataDefinition().getType());
- this.setDescription ( ctd.getCapabilityTypeDataDefinition().getDescription());
- this.setValidSourceTypes( ctd.getCapabilityTypeDataDefinition().getValidSourceTypes());
- }
-
+ public CapabilityTypeDefinition(CapabilityTypeData ctd) {
+ this.setUniqueId(ctd.getUniqueId());
+ this.setType(ctd.getCapabilityTypeDataDefinition().getType());
+ this.setDescription(ctd.getCapabilityTypeDataDefinition().getDescription());
+ this.setValidSourceTypes(ctd.getCapabilityTypeDataDefinition().getValidSourceTypes());
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabiltyInstance.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabiltyInstance.java
index c10521da95..3bcdf5589d 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabiltyInstance.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabiltyInstance.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import java.util.Map;
@@ -25,7 +24,6 @@ import java.util.Map;
public class CapabiltyInstance {
private String uniqueId;
-
private Map<String, String> properties;
public String getUniqueId() {
@@ -48,5 +46,4 @@ public class CapabiltyInstance {
public String toString() {
return "CapabiltyInstance [uniqueId=" + uniqueId + ", properties=" + properties + "]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CatalogUpdateTimestamp.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CatalogUpdateTimestamp.java
index 5b9c5cbe7a..7bcb8aa39a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CatalogUpdateTimestamp.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CatalogUpdateTimestamp.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -42,5 +41,4 @@ public class CatalogUpdateTimestamp {
public static CatalogUpdateTimestamp buildDummyCatalogUpdateTimestamp() {
return new CatalogUpdateTimestamp(0L, System.currentTimeMillis());
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Category.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Category.java
index 33d69ac721..18e897ccce 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Category.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Category.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
public class Category {
@@ -42,18 +41,23 @@ public class Category {
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
Category other = (Category) obj;
if (name == null) {
- if (other.name != null)
+ if (other.name != null) {
return false;
- } else if (!name.equals(other.name))
+ }
+ } else if (!name.equals(other.name)) {
return false;
+ }
return true;
}
@@ -61,5 +65,4 @@ public class Category {
public String toString() {
return "Category [name=" + name + "]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Combination.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Combination.java
index 0ea79d975c..adeb18a9f0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Combination.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Combination.java
@@ -16,10 +16,9 @@
*
*
*/
-
package org.openecomp.sdc.be.model;
-import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;
import java.util.Map;
import lombok.Getter;
@@ -45,5 +44,4 @@ public class Combination {
name = UICombination.getName();
description = UICombination.getDescription();
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java
index c40eef3309..05cf94a266 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import static java.util.Collections.emptyList;
@@ -92,9 +91,9 @@ public abstract class Component implements PropertiesOwner {
private Map<String, InterfaceDefinition> interfaces;
private List<DataTypeDefinition> dataTypes;
private SubstitutionFilterDataDefinition substitutionFilter;
-
- public void setCategorySpecificMetadata(final Map<String, String> categorySpecificMetadata) {
- componentMetadataDefinition.getMetadataDataDefinition().setCategorySpecificMetadata(categorySpecificMetadata);
+
+ protected Component(ComponentMetadataDefinition componentMetadataDefinition) {
+ this.componentMetadataDefinition = componentMetadataDefinition;
}
public Map<String, String> getCategorySpecificMetadata() {
@@ -102,8 +101,8 @@ public abstract class Component implements PropertiesOwner {
return categorySpecificMetadata == null ? Collections.emptyMap() : categorySpecificMetadata;
}
- protected Component(ComponentMetadataDefinition componentMetadataDefinition) {
- this.componentMetadataDefinition = componentMetadataDefinition;
+ public void setCategorySpecificMetadata(final Map<String, String> categorySpecificMetadata) {
+ componentMetadataDefinition.getMetadataDataDefinition().setCategorySpecificMetadata(categorySpecificMetadata);
}
@JsonIgnore
@@ -302,14 +301,14 @@ public abstract class Component implements PropertiesOwner {
return this.componentMetadataDefinition.getMetadataDataDefinition().getComponentType();
}
- public boolean isService() {
- return getComponentType() == ComponentTypeEnum.SERVICE;
- }
-
public void setComponentType(ComponentTypeEnum componentType) {
this.componentMetadataDefinition.getMetadataDataDefinition().setComponentType(componentType);
}
+ public boolean isService() {
+ return getComponentType() == ComponentTypeEnum.SERVICE;
+ }
+
public Map<String, List<CapabilityDefinition>> getCapabilities() {
if (MapUtils.isEmpty(capabilities)) {
capabilities = Maps.newHashMap();
@@ -330,19 +329,16 @@ public abstract class Component implements PropertiesOwner {
}
public Map<String, ArtifactDefinition> safeGetComponentInstanceDeploymentArtifacts(String componentInstanceId) {
- return getComponentInstanceById(componentInstanceId).map(ComponentInstance::safeGetDeploymentArtifacts)
- .orElse(emptyMap());
+ return getComponentInstanceById(componentInstanceId).map(ComponentInstance::safeGetDeploymentArtifacts).orElse(emptyMap());
}
public Map<String, ArtifactDefinition> safeGetComponentInstanceInformationalArtifacts(String componentInstanceId) {
- return getComponentInstanceById(componentInstanceId).map(ComponentInstance::safeGetInformationalArtifacts)
- .orElse(emptyMap());
+ return getComponentInstanceById(componentInstanceId).map(ComponentInstance::safeGetInformationalArtifacts).orElse(emptyMap());
}
public List<ArtifactDefinition> safeGetComponentInstanceHeatArtifacts(String componentInstanceId) {
return safeGetComponentInstanceDeploymentArtifacts(componentInstanceId).values().stream()
- .filter(artifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(artifact.getArtifactType()))
- .collect(Collectors.toList());
+ .filter(artifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(artifact.getArtifactType())).collect(Collectors.toList());
}
public Map<String, List<ComponentInstanceProperty>> safeGetComponentInstancesProperties() {
@@ -358,8 +354,8 @@ public abstract class Component implements PropertiesOwner {
}
private Map<String, List<ComponentInstanceProperty>> findUiComponentInstancesProperties() {
- List<String> instancesFromUi = componentInstances.stream().filter(i -> !i.isCreatedFromCsar())
- .map(ComponentInstance::getUniqueId).collect(Collectors.toList());
+ List<String> instancesFromUi = componentInstances.stream().filter(i -> !i.isCreatedFromCsar()).map(ComponentInstance::getUniqueId)
+ .collect(Collectors.toList());
return componentInstancesProperties.entrySet().stream().filter(e -> instancesFromUi.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
@@ -373,8 +369,8 @@ public abstract class Component implements PropertiesOwner {
}
private Map<String, List<ComponentInstanceInput>> findUiComponentInstancesInputs() {
- List<String> instancesFromUi = componentInstances.stream().filter(i -> !i.isCreatedFromCsar())
- .map(ComponentInstance::getUniqueId).collect(Collectors.toList());
+ List<String> instancesFromUi = componentInstances.stream().filter(i -> !i.isCreatedFromCsar()).map(ComponentInstance::getUniqueId)
+ .collect(Collectors.toList());
return componentInstancesInputs.entrySet().stream().filter(e -> instancesFromUi.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
@@ -488,7 +484,6 @@ public abstract class Component implements PropertiesOwner {
if (MapUtils.isEmpty(this.policies)) {
this.policies = new HashMap<>();
}
-
this.policies.put(policyDefinition.getUniqueId(), policyDefinition);
}
@@ -496,7 +491,6 @@ public abstract class Component implements PropertiesOwner {
if (org.apache.commons.collections.CollectionUtils.isEmpty(this.properties)) {
this.properties = new ArrayList<>();
}
-
this.properties.add(propertyDefinition);
}
@@ -595,10 +589,8 @@ public abstract class Component implements PropertiesOwner {
if (this.componentInstancesInputs == null) {
return emptyPropsList;
}
- return this.componentInstances.stream().filter(ci -> ci.getName().equals(cmptInstanceName))
- .map(ComponentInstance::getUniqueId)
- .map(instanceId -> safeGetComponentInstanceEntity(instanceId, this.componentInstancesInputs)).findAny()
- .orElse(emptyPropsList);
+ return this.componentInstances.stream().filter(ci -> ci.getName().equals(cmptInstanceName)).map(ComponentInstance::getUniqueId)
+ .map(instanceId -> safeGetComponentInstanceEntity(instanceId, this.componentInstancesInputs)).findAny().orElse(emptyPropsList);
}
private <T> List<T> safeGetComponentInstanceEntity(String cmptInstanceId, Map<String, List<T>> instanceEntities) {
@@ -615,8 +607,7 @@ public abstract class Component implements PropertiesOwner {
}
public String fetchGenericTypeToscaNameFromConfig() {
- return ConfigurationManager.getConfigurationManager().getConfiguration().getGenericAssetNodeTypes()
- .get(this.assetType());
+ return ConfigurationManager.getConfigurationManager().getConfiguration().getGenericAssetNodeTypes().get(this.assetType());
}
protected <A> Optional<A> getHeadOption(List<A> list) {
@@ -715,5 +706,4 @@ public abstract class Component implements PropertiesOwner {
componentMetadata.put(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_VERSION, this.getCsarVersion());
return componentMetadata;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentDependency.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentDependency.java
index ab4463caea..746237760d 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentDependency.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentDependency.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
+import java.util.ArrayList;
+import java.util.List;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
-import java.util.ArrayList;
-import java.util.List;
-
@Getter
@Setter
@NoArgsConstructor
public class ComponentDependency {
+
private String name;
private String version;
private String uniqueId;
@@ -38,18 +37,17 @@ public class ComponentDependency {
private String icon;
private String state;
private List<String> instanceNames;
-
private List<ComponentDependency> dependencies;
public void addDependencies(List<ComponentDependency> dependencies) {
- if ( this.dependencies == null ){
+ if (this.dependencies == null) {
this.dependencies = new ArrayList<>();
}
this.dependencies.addAll(dependencies);
- }
+ }
- public void addDependency(ComponentDependency dependency){
- if ( dependencies == null ){
+ public void addDependency(ComponentDependency dependency) {
+ if (dependencies == null) {
dependencies = new ArrayList<>();
}
dependencies.add(dependency);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java
index a660c0da6d..8324478299 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java
@@ -17,16 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
-import org.apache.commons.lang3.tuple.Pair;
+import static org.apache.commons.collections.MapUtils.isNotEmpty;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
-import static org.apache.commons.collections.MapUtils.isNotEmpty;
+import org.apache.commons.lang3.tuple.Pair;
public class ComponentInstInputsMap {
@@ -48,13 +46,13 @@ public class ComponentInstInputsMap {
if (isNotEmpty(policyProperties)) {
return singleMapEntry(policyProperties);
}
- if(isNotEmpty(serviceProperties)) {
+ if (isNotEmpty(serviceProperties)) {
return singleMapEntry(serviceProperties);
}
if (isNotEmpty(groupProperties)) {
return singleMapEntry(groupProperties);
}
- if(isNotEmpty(componentPropertiesToPolicies)) {
+ if (isNotEmpty(componentPropertiesToPolicies)) {
return singleMapEntry(componentPropertiesToPolicies);
}
if (isNotEmpty(componentInstancePropertiesToPolicies)) {
@@ -96,8 +94,7 @@ public class ComponentInstInputsMap {
return serviceProperties;
}
- public void setServiceProperties(
- Map<String, List<ComponentInstancePropInput>> serviceProperties) {
+ public void setServiceProperties(Map<String, List<ComponentInstancePropInput>> serviceProperties) {
this.serviceProperties = serviceProperties;
}
@@ -124,6 +121,4 @@ public class ComponentInstInputsMap {
public void setComponentInstancePropertiesToPolicies(Map<String, List<ComponentInstancePropInput>> componentInstancePropertiesToPolicies) {
this.componentInstancePropertiesToPolicies = componentInstancePropertiesToPolicies;
}
-
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstListInput.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstListInput.java
index ee4bef2236..7836103ff5 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstListInput.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstListInput.java
@@ -17,14 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
/**
- * Represents a pair of a list of properties to be declared and a "list input" to be created.
- * This class is used for passing parameters on creating a list input.
+ * Represents a pair of a list of properties to be declared and a "list input" to be created. This class is used for passing parameters on creating a
+ * list input.
*/
public class ComponentInstListInput {
+
private ComponentInstInputsMap componentInstInputsMap;
private InputDefinition listInput;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstOutputsMap.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstOutputsMap.java
index 98b39fd1c2..20113579f8 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstOutputsMap.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstOutputsMap.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import static org.apache.commons.collections.MapUtils.isNotEmpty;
@@ -29,7 +28,7 @@ import lombok.Setter;
import org.apache.commons.lang3.tuple.Pair;
@Setter
-public class ComponentInstOutputsMap {
+public class ComponentInstOutputsMap {
private Map<String, List<ComponentInstanceAttribOutput>> componentInstanceOutputsMap;
private Map<String, List<ComponentInstanceAttribOutput>> componentInstanceAttributes;
@@ -56,5 +55,4 @@ public class ComponentInstOutputsMap {
public Map<String, List<ComponentInstanceAttribOutput>> getComponentInstanceAttributes() {
return componentInstanceAttributes == null ? new HashMap<>() : componentInstanceAttributes;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java
index dd8296e8f7..d11f1ffb93 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.Collections;
@@ -99,5 +98,4 @@ public class ComponentInstance extends ComponentInstanceDataDefinition implement
public boolean isCreatedFromCsar() {
return CreatedFrom.CSAR.equals(this.getCreatedFrom());
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribOutput.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribOutput.java
index 9b14e1af54..8531a36843 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribOutput.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribOutput.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import lombok.Getter;
@@ -45,5 +44,4 @@ public class ComponentInstanceAttribOutput extends ComponentInstanceAttribute {
}
return tokens;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java
index af2964ff40..060219937e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.List;
@@ -30,24 +29,18 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
@Setter
public class ComponentInstanceAttribute extends AttributeDefinition implements IComponentInstanceConnectedElement, IAttributeOutputCommon {
- public ComponentInstanceAttribute(final AttributeDataDefinition value) {
- super(value);
- }
- public ComponentInstanceAttribute() {
- super();
- }
-
/**
* The unique id of the property value on graph
*/
private String valueUniqueUid;
-
private List<String> path;
-
- private List<PropertyRule> rules ;
-
+ private List<PropertyRule> rules;
private String componentInstanceName;
-
private String componentInstanceId;
-
+ public ComponentInstanceAttribute(final AttributeDataDefinition value) {
+ super(value);
+ }
+ public ComponentInstanceAttribute() {
+ super();
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java
index d97db3fb8b..f70ac0d5f7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
+import java.util.List;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
-import java.util.List;
-
public class ComponentInstanceInput extends InputDefinition implements IComponentInstanceConnectedElement, IPropertyInputCommon {
/**
* The unique id of the property value on graph
*/
private String valueUniqueUid;
-
private List<String> path = null;
-
private List<PropertyRule> rules = null;
private String componentInstanceName;
private String componentInstanceId;
@@ -42,8 +38,7 @@ public class ComponentInstanceInput extends InputDefinition implements IComponen
super();
}
- public ComponentInstanceInput(PropertyDataDefinition curPropertyDef, String inputId, String value,
- String valueUniqueUid) {
+ public ComponentInstanceInput(PropertyDataDefinition curPropertyDef, String inputId, String value, String valueUniqueUid) {
super(curPropertyDef);
setInputId(inputId);
setValue(value);
@@ -52,14 +47,13 @@ public class ComponentInstanceInput extends InputDefinition implements IComponen
public ComponentInstanceInput(InputDefinition pd, String value, String valueUniqueUid) {
super(pd);
-
setValue(value);
this.valueUniqueUid = valueUniqueUid;
}
public ComponentInstanceInput(PropertyDataDefinition propertyDefinition) {
super(propertyDefinition);
- if(propertyDefinition.getGetInputValues() != null && !propertyDefinition.getGetInputValues().isEmpty()){
+ if (propertyDefinition.getGetInputValues() != null && !propertyDefinition.getGetInputValues().isEmpty()) {
setInputId(propertyDefinition.getGetInputValues().get(0).getInputId());
}
}
@@ -106,8 +100,7 @@ public class ComponentInstanceInput extends InputDefinition implements IComponen
@Override
public String toString() {
- return "ComponentInstanceInput [ " + super.toString() + " , value=" + getValue() + ", valueUniqueUid = "
- + valueUniqueUid + " , rules=" + rules + " , path=" + path + " ]";
+ return "ComponentInstanceInput [ " + super.toString() + " , value=" + getValue() + ", valueUniqueUid = " + valueUniqueUid + " , rules="
+ + rules + " , path=" + path + " ]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInterface.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInterface.java
index 487d642a5c..5d41c63454 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInterface.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInterface.java
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.model;
import lombok.Getter;
@@ -26,18 +25,17 @@ import org.openecomp.sdc.be.datatypes.elements.InterfaceInstanceDataDefinition;
@Setter
@NoArgsConstructor
public class ComponentInstanceInterface extends InterfaceDefinition {
- private String interfaceId;
- private InterfaceInstanceDataDefinition interfaceInstanceDataDefinition;
- public ComponentInstanceInterface(String interfaceId,
- InterfaceInstanceDataDefinition interfaceInstanceDataDefinition) {
- this.interfaceId = interfaceId;
- this.interfaceInstanceDataDefinition = interfaceInstanceDataDefinition;
- }
+ private String interfaceId;
+ private InterfaceInstanceDataDefinition interfaceInstanceDataDefinition;
- public ComponentInstanceInterface(String interfaceId, InterfaceDataDefinition interfaceDataDefinition) {
- super(interfaceDataDefinition);
- this.interfaceId = interfaceId;
- }
+ public ComponentInstanceInterface(String interfaceId, InterfaceInstanceDataDefinition interfaceInstanceDataDefinition) {
+ this.interfaceId = interfaceId;
+ this.interfaceInstanceDataDefinition = interfaceInstanceDataDefinition;
+ }
+ public ComponentInstanceInterface(String interfaceId, InterfaceDataDefinition interfaceDataDefinition) {
+ super(interfaceDataDefinition);
+ this.interfaceId = interfaceId;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceOutput.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceOutput.java
index be3f87eb9b..6b8c7cf691 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceOutput.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceOutput.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.List;
@@ -38,16 +37,12 @@ public class ComponentInstanceOutput extends OutputDefinition implements ICompon
* The unique id of the attribute value on graph
*/
private String valueUniqueUid;
-
private List<String> path;
-
private List<PropertyRule> rules;
private String componentInstanceName;
private String componentInstanceId;
- public ComponentInstanceOutput(final AttributeDataDefinition curPropertyDef,
- final String outputId,
- final String value,
+ public ComponentInstanceOutput(final AttributeDataDefinition curPropertyDef, final String outputId, final String value,
final String valueUniqueUid) {
super(curPropertyDef);
setOutputId(outputId);
@@ -55,21 +50,16 @@ public class ComponentInstanceOutput extends OutputDefinition implements ICompon
this.valueUniqueUid = valueUniqueUid;
}
- public ComponentInstanceOutput(final OutputDefinition pd,
- final String value,
- final String valueUniqueUid) {
+ public ComponentInstanceOutput(final OutputDefinition pd, final String value, final String valueUniqueUid) {
super(pd);
-
setValue(value);
this.valueUniqueUid = valueUniqueUid;
}
public ComponentInstanceOutput(AttributeDataDefinition attributeDataDefinition) {
super(attributeDataDefinition);
- if (attributeDataDefinition.getGetOutputValues() != null && !attributeDataDefinition.getGetOutputValues()
- .isEmpty()) {
+ if (attributeDataDefinition.getGetOutputValues() != null && !attributeDataDefinition.getGetOutputValues().isEmpty()) {
setOutputId(attributeDataDefinition.getGetOutputValues().get(0).getOutputId());
}
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstancePropInput.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstancePropInput.java
index 80cf424978..048a952bd8 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstancePropInput.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstancePropInput.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
public class ComponentInstancePropInput extends ComponentInstanceProperty {
@@ -36,22 +35,24 @@ public class ComponentInstancePropInput extends ComponentInstanceProperty {
public String getPropertiesName() {
return propertiesName;
}
+
public void setPropertiesName(String propertiesName) {
this.propertiesName = propertiesName;
}
+
public PropertyDefinition getInput() {
return input;
}
+
public void setInput(PropertyDefinition input) {
this.input = input;
}
- public String[] getParsedPropNames(){
+ public String[] getParsedPropNames() {
String[] tokens = null;
- if(propertiesName != null && !propertiesName.isEmpty()){
+ if (propertiesName != null && !propertiesName.isEmpty()) {
tokens = propertiesName.split("#");
}
return tokens;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
index c318c9f8db..7e0342866f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,49 +17,27 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
+import java.util.List;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
-import java.util.List;
-
public class ComponentInstanceProperty extends PropertyDefinition implements IComponentInstanceConnectedElement, IPropertyInputCommon {
/**
* The unique id of the property value on graph
*/
private String valueUniqueUid;
-
private List<String> path;
-
- private List<PropertyRule> rules ;
-
-
+ private List<PropertyRule> rules;
private String componentInstanceName;
-
private String componentInstanceId;
- public String getComponentInstanceName() {
- return componentInstanceName;
- }
-
- public void setComponentInstanceName(String componentInstanceName) {
- this.componentInstanceName = componentInstanceName;
- }
-
- public String getComponentInstanceId() {
- return componentInstanceId;
- }
-
- public void setComponentInstanceId(String componentInstanceId) {
- this.componentInstanceId = componentInstanceId;
- }
-
public ComponentInstanceProperty() {
super();
}
+
public ComponentInstanceProperty(PropertyDataDefinition pd) {
super(pd);
getConstraints();
@@ -71,20 +49,32 @@ public class ComponentInstanceProperty extends PropertyDefinition implements ICo
public ComponentInstanceProperty(PropertyDefinition pd, String value, String valueUniqueUid) {
super(pd);
-
this.setValue(value);
this.valueUniqueUid = valueUniqueUid;
}
public ComponentInstanceProperty(Boolean hidden, PropertyDefinition pd, String valueUniqueUid) {
super(pd);
-
this.hidden = hidden;
this.valueUniqueUid = valueUniqueUid;
setParentUniqueId(pd.getParentUniqueId());
}
+ public String getComponentInstanceName() {
+ return componentInstanceName;
+ }
+
+ public void setComponentInstanceName(String componentInstanceName) {
+ this.componentInstanceName = componentInstanceName;
+ }
+
+ public String getComponentInstanceId() {
+ return componentInstanceId;
+ }
+ public void setComponentInstanceId(String componentInstanceId) {
+ this.componentInstanceId = componentInstanceId;
+ }
public String getValueUniqueUid() {
return valueUniqueUid;
@@ -94,7 +84,6 @@ public class ComponentInstanceProperty extends PropertyDefinition implements ICo
this.valueUniqueUid = valueUniqueUid;
}
-
public List<String> getPath() {
return path;
}
@@ -111,16 +100,15 @@ public class ComponentInstanceProperty extends PropertyDefinition implements ICo
this.rules = rules;
}
-
@Override
public String toString() {
- return "ComponentInstanceProperty [ " + super.toString() + " , value=" + getValue() + ", valueUniqueUid = " + valueUniqueUid + " , rules=" + rules + " , path=" + path + " ]";
+ return "ComponentInstanceProperty [ " + super.toString() + " , value=" + getValue() + ", valueUniqueUid = " + valueUniqueUid + " , rules="
+ + rules + " , path=" + path + " ]";
}
-
- public void updateCapabilityProperty(ComponentInstanceProperty property) {
- if(property != null && property.getValue() != null){
- setValue(property.getValue());
- }
- }
+ public void updateCapabilityProperty(ComponentInstanceProperty property) {
+ if (property != null && property.getValue() != null) {
+ setValue(property.getValue());
+ }
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentMetadataDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentMetadataDefinition.java
index a126a747ef..409eab14a8 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentMetadataDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentMetadataDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
@@ -27,7 +26,6 @@ public class ComponentMetadataDefinition {
protected ComponentMetadataDataDefinition componentMetadataDataDefinition;
public ComponentMetadataDefinition() {
-
}
public ComponentMetadataDefinition(ComponentMetadataDataDefinition component) {
@@ -42,26 +40,29 @@ public class ComponentMetadataDefinition {
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result
- + ((componentMetadataDataDefinition == null) ? 0 : componentMetadataDataDefinition.hashCode());
+ result = prime * result + ((componentMetadataDataDefinition == null) ? 0 : componentMetadataDataDefinition.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
ComponentMetadataDefinition other = (ComponentMetadataDefinition) obj;
if (componentMetadataDataDefinition == null) {
- if (other.componentMetadataDataDefinition != null)
+ if (other.componentMetadataDataDefinition != null) {
return false;
- } else if (!componentMetadataDataDefinition.equals(other.componentMetadataDataDefinition))
+ }
+ } else if (!componentMetadataDataDefinition.equals(other.componentMetadataDataDefinition)) {
return false;
+ }
return true;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java
index 4c8cb3d866..e55c454829 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.List;
@@ -71,7 +70,6 @@ public class ComponentParametersView {
public ComponentParametersView(List<String> filters) {
this(true);
-
for (String fieldName : filters) {
switch (ComponentFieldsEnum.findByValue(fieldName)) {
case PROPERTIES:
@@ -183,15 +181,14 @@ public class ComponentParametersView {
default:
break;
}
-
}
}
-
///////////////////////////////////////////////////////////////
+
// When adding new member, please update the filter method.
+
///////////////////////////////////////////////////////////////
public Component filter(Component component, ComponentTypeEnum componentType) {
-
if (ignoreUsers) {
component.setCreatorUserId(null);
component.setCreatorFullName(null);
@@ -238,8 +235,7 @@ public class ComponentParametersView {
if (ignoreNodeFilterRequirements) {
component.setNodeFilterComponents(null);
}
- if (ignoreInterfaces && ignoreInterfaceInstances &&
- componentType == ComponentTypeEnum.RESOURCE) {
+ if (ignoreInterfaces && ignoreInterfaceInstances && componentType == ComponentTypeEnum.RESOURCE) {
component.setInterfaces(null);
}
if (ignoreDerivedFrom && componentType == ComponentTypeEnum.RESOURCE) {
@@ -322,5 +318,4 @@ public class ComponentParametersView {
}
return parseFlag;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ConsumerDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ConsumerDefinition.java
index 7fde867578..195cb4f07a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ConsumerDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ConsumerDefinition.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DataTypeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DataTypeDefinition.java
index 7cdf932ce9..6c285802d2 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DataTypeDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DataTypeDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
+import java.util.List;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@@ -27,8 +27,6 @@ import lombok.ToString;
import org.openecomp.sdc.be.dao.utils.CollectionUtils;
import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
-import java.util.List;
-
@Getter
@Setter
@NoArgsConstructor
@@ -36,9 +34,7 @@ import java.util.List;
public class DataTypeDefinition extends DataTypeDataDefinition {
private DataTypeDefinition derivedFrom;
-
private List<PropertyConstraint> constraints;
-
private List<PropertyDefinition> properties;
public DataTypeDefinition(DataTypeDataDefinition p) {
@@ -57,5 +53,4 @@ public class DataTypeDefinition extends DataTypeDataDefinition {
public List<PropertyConstraint> safeGetConstraints() {
return CollectionUtils.safeGetList(constraints);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java
index 5a670890a9..934a43bc38 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import fj.data.Either;
+import java.util.List;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
-import java.util.List;
-
public interface DerivedNodeTypeResolver {
Either<List<GraphVertex>, JanusGraphOperationStatus> findDerivedResources(String parentResource);
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java
index 3826e18853..e81be9f09e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
public enum DistributionStatusEnum {
DISTRIBUTION_NOT_APPROVED("Distribution not approved"), DISTRIBUTED("Distributed");
-
private String value;
private DistributionStatusEnum(String value) {
this.value = value;
}
- public String getValue() {
- return value;
- }
-
public static DistributionStatusEnum findState(String state) {
-
for (DistributionStatusEnum distributionStatus : DistributionStatusEnum.values()) {
if (distributionStatus.name().equalsIgnoreCase(state) || distributionStatus.getValue().equalsIgnoreCase(state)) {
return distributionStatus;
@@ -43,4 +36,7 @@ public enum DistributionStatusEnum {
return null;
}
+ public String getValue() {
+ return value;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionTransitionEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionTransitionEnum.java
index 715ae9cc21..badc43f008 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionTransitionEnum.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionTransitionEnum.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
public enum DistributionTransitionEnum {
APPROVE("approve"), REJECT("reject");
-
String displayName;
private DistributionTransitionEnum(String displayName) {
this.displayName = displayName;
}
- public String getDisplayName() {
- return displayName;
- }
-
public static DistributionTransitionEnum getFromDisplayName(String name) {
-
for (DistributionTransitionEnum val : DistributionTransitionEnum.values()) {
if (name.equalsIgnoreCase(val.getDisplayName())) {
return val;
@@ -51,4 +44,7 @@ public enum DistributionTransitionEnum {
return sb.toString();
}
+ public String getDisplayName() {
+ return displayName;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/FunctionalMenuInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/FunctionalMenuInfo.java
index 40cfd50fff..db25e4b0c0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/FunctionalMenuInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/FunctionalMenuInfo.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
public class FunctionalMenuInfo {
@@ -40,5 +39,4 @@ public class FunctionalMenuInfo {
public String toString() {
return "FunctionalMenuInfo [functionalMenu=" + functionalMenu + "]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java
index 3a83533f85..843ff898de 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.Collectors.toMap;
+
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
@@ -31,17 +37,11 @@ import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
+public class GroupDefinition extends GroupDataDefinition implements PropertiesOwner {
-import static java.util.stream.Collectors.*;
+ @JsonInclude
+ private Map<String, List<CapabilityDefinition>> capabilities;
-public class GroupDefinition extends GroupDataDefinition implements PropertiesOwner{
-
- @JsonInclude
- private Map<String, List<CapabilityDefinition>> capabilities;
-
public GroupDefinition() {
super();
}
@@ -51,81 +51,77 @@ public class GroupDefinition extends GroupDataDefinition implements PropertiesOw
}
public GroupDefinition(GroupDefinition other) {
- super(other);
- if(MapUtils.isNotEmpty(other.getCapabilities())) {
- this.setCapabilities(other.getCapabilities().entrySet()
- .stream()
- .collect(toMap(Map.Entry::getKey, e -> getCapabilitiesCopyList(e.getValue()))));
- }
- }
-
- public Map<String, List<CapabilityDefinition>> getCapabilities() {
- if(MapUtils.isEmpty(capabilities)) {
- capabilities = Maps.newHashMap();
- }
- return capabilities;
- }
-
- public void setCapabilities(Map<String, List<CapabilityDefinition>> capabilities) {
- this.capabilities = capabilities;
+ super(other);
+ if (MapUtils.isNotEmpty(other.getCapabilities())) {
+ this.setCapabilities(
+ other.getCapabilities().entrySet().stream().collect(toMap(Map.Entry::getKey, e -> getCapabilitiesCopyList(e.getValue()))));
+ }
+ }
+
+ public Map<String, List<CapabilityDefinition>> getCapabilities() {
+ if (MapUtils.isEmpty(capabilities)) {
+ capabilities = Maps.newHashMap();
+ }
+ return capabilities;
+ }
+
+ public void setCapabilities(Map<String, List<CapabilityDefinition>> capabilities) {
+ this.capabilities = capabilities;
}
public List<GroupProperty> convertToGroupProperties() {
List<GroupProperty> properties = null;
List<PropertyDataDefinition> propList = super.getProperties();
- if(propList != null && !propList .isEmpty()){
- properties = propList.stream().map(GroupProperty::new).collect(toList());
+ if (propList != null && !propList.isEmpty()) {
+ properties = propList.stream().map(GroupProperty::new).collect(toList());
}
return properties;
}
public <T extends PropertyDataDefinition> void convertFromGroupProperties(List<T> properties) {
- if(properties != null && !properties .isEmpty()){
- List<PropertyDataDefinition> propList = properties.stream().map(PropertyDataDefinition::new).collect(toList());
+ if (properties != null && !properties.isEmpty()) {
+ List<PropertyDataDefinition> propList = properties.stream().map(PropertyDataDefinition::new).collect(toList());
super.setProperties(propList);
}
- }
-
+ }
+
//returns true iff groupName has the same prefix has the resource
- public boolean isSamePrefix(String resourceName){
- return getName() != null && getName().toLowerCase().trim().startsWith(resourceName.toLowerCase());
+ public boolean isSamePrefix(String resourceName) {
+ return getName() != null && getName().toLowerCase().trim().startsWith(resourceName.toLowerCase());
}
public void convertCapabilityDefinitions(Map<String, CapabilityDefinition> capabilities) {
- if(MapUtils.isNotEmpty(capabilities)){
- this.capabilities = capabilities.values().stream()
- .collect(groupingBy(CapabilityDefinition::getType));
+ if (MapUtils.isNotEmpty(capabilities)) {
+ this.capabilities = capabilities.values().stream().collect(groupingBy(CapabilityDefinition::getType));
+ }
+ }
+
+ @Override
+ public String getNormalizedName() {
+ return getName();
+ }
+
+ @JsonIgnore
+ private List<CapabilityDefinition> getCapabilitiesCopyList(List<CapabilityDefinition> capabilities) {
+ return Lists.newArrayList(capabilities.stream().map(CapabilityDefinition::new).collect(toList()));
+ }
+
+ public void updateCapabilitiesProperties(Map<String, Map<String, CapabilityDefinition>> capabilitiesInfo) {
+ if (MapUtils.isNotEmpty(capabilities) && MapUtils.isNotEmpty(capabilitiesInfo)) {
+ capabilities.entrySet().forEach(e -> updateCapabilitiesProperies(e.getValue(), capabilitiesInfo.get(e.getKey())));
}
}
- @Override
- public String getNormalizedName() {
- return getName();
- }
-
- @JsonIgnore
- private List<CapabilityDefinition> getCapabilitiesCopyList(List<CapabilityDefinition> capabilities) {
- return Lists.newArrayList(capabilities.stream().map(CapabilityDefinition::new).collect(toList()));
- }
-
- public void updateCapabilitiesProperties(Map<String, Map<String, CapabilityDefinition>> capabilitiesInfo) {
- if(MapUtils.isNotEmpty(capabilities) && MapUtils.isNotEmpty(capabilitiesInfo)){
- capabilities.entrySet().forEach(e->updateCapabilitiesProperies(e.getValue(), capabilitiesInfo.get(e.getKey())));
- }
- }
-
- private void updateCapabilitiesProperies(List<CapabilityDefinition> capabilities, Map<String, CapabilityDefinition> capabilitiesInfo) {
- if(CollectionUtils.isNotEmpty(capabilities) && MapUtils.isNotEmpty(capabilitiesInfo)){
- capabilities.forEach(c->c.updateCapabilityProperties(capabilitiesInfo.get(c.getName())));
- }
- }
-
- public void updateEmptyCapabilitiesOwnerFields(){
- if(MapUtils.isNotEmpty(this.capabilities)){
- this.capabilities.values().stream()
- .flatMap(Collection::stream)
- .forEach(c -> c.updateEmptyCapabilityOwnerFields(getUniqueId(), getName(), CapabilityDataDefinition.OwnerType.GROUP));
- }
- }
+ private void updateCapabilitiesProperies(List<CapabilityDefinition> capabilities, Map<String, CapabilityDefinition> capabilitiesInfo) {
+ if (CollectionUtils.isNotEmpty(capabilities) && MapUtils.isNotEmpty(capabilitiesInfo)) {
+ capabilities.forEach(c -> c.updateCapabilityProperties(capabilitiesInfo.get(c.getName())));
+ }
+ }
+ public void updateEmptyCapabilitiesOwnerFields() {
+ if (MapUtils.isNotEmpty(this.capabilities)) {
+ this.capabilities.values().stream().flatMap(Collection::stream)
+ .forEach(c -> c.updateEmptyCapabilityOwnerFields(getUniqueId(), getName(), CapabilityDataDefinition.OwnerType.GROUP));
+ }
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java
index ca154f3076..386febdf86 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
+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 org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
@@ -27,11 +32,10 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.*;
-import java.util.stream.Collectors;
-
public class GroupInstance extends GroupInstanceDataDefinition {
+ private static final Logger log = Logger.getLogger(GroupInstance.class);
+
public GroupInstance() {
super();
}
@@ -40,25 +44,28 @@ public class GroupInstance extends GroupInstanceDataDefinition {
super(r);
}
- private static final Logger log = Logger.getLogger(GroupInstance.class);
/**
* Converts contained list of PropertyDataDefinitions to list of GroupInstanceProperties
+ *
* @return
*/
- public List<GroupInstanceProperty> convertToGroupInstancesProperties() {
+ public List<GroupInstanceProperty> convertToGroupInstancesProperties() {
List<GroupInstanceProperty> groupInstancesProperties = null;
List<PropertyDataDefinition> propertiesList = super.getProperties();
- if(propertiesList != null && !propertiesList .isEmpty()){
+ if (propertiesList != null && !propertiesList.isEmpty()) {
groupInstancesProperties = propertiesList.stream().map(GroupInstanceProperty::new).collect(Collectors.toList());
}
return groupInstancesProperties;
}
+
/**
- * Converts received list of GroupInstanceProperties to the list of PropertyDataDefinitions and sets It into the GroupInstanceDataDefinition as properties
+ * Converts received list of GroupInstanceProperties to the list of PropertyDataDefinitions and sets It into the GroupInstanceDataDefinition as
+ * properties
+ *
* @param groupInstancesProperties
*/
public void convertFromGroupInstancesProperties(List<GroupInstanceProperty> groupInstancesProperties) {
- if(groupInstancesProperties != null && !groupInstancesProperties .isEmpty()){
+ if (groupInstancesProperties != null && !groupInstancesProperties.isEmpty()) {
List<PropertyDataDefinition> propList = groupInstancesProperties.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
super.setProperties(propList);
}
@@ -67,71 +74,65 @@ public class GroupInstance extends GroupInstanceDataDefinition {
private void removeArtifactsDuplicates() {
List<String> artifacts = getArtifacts();
Set<String> artifactsSet = new HashSet<>();
-
- if (artifacts != null && !artifacts.isEmpty()) {
- artifactsSet.addAll(artifacts);
- artifacts.clear();
- artifacts.addAll(artifactsSet);
- }
-
+ if (artifacts != null && !artifacts.isEmpty()) {
+ artifactsSet.addAll(artifacts);
+ artifacts.clear();
+ artifacts.addAll(artifactsSet);
+ }
List<String> giArtifacts = getGroupInstanceArtifacts();
Set<String> giArtifactsSet = new HashSet<>();
-
- if (giArtifacts != null && !giArtifacts.isEmpty()) {
- giArtifactsSet.addAll(giArtifacts);
- giArtifacts.clear();
- giArtifacts.addAll(giArtifactsSet);
- }
- }
+ if (giArtifacts != null && !giArtifacts.isEmpty()) {
+ giArtifactsSet.addAll(giArtifacts);
+ giArtifacts.clear();
+ giArtifacts.addAll(giArtifactsSet);
+ }
+ }
private void clearArtifactsUuid() {
List<String> artifactsUuid = getArtifactsUuid();
- if(CollectionUtils.isNotEmpty(artifactsUuid)){
+ if (CollectionUtils.isNotEmpty(artifactsUuid)) {
artifactsUuid.clear();
- } else if (artifactsUuid == null){
+ } else if (artifactsUuid == null) {
setArtifactsUuid(new ArrayList<>());
}
-
List<String> giartifactsUuid = this.getGroupInstanceArtifactsUuid();
- if(CollectionUtils.isNotEmpty(giartifactsUuid)){
+ if (CollectionUtils.isNotEmpty(giartifactsUuid)) {
giartifactsUuid.clear();
- } else if (giartifactsUuid == null){
+ } else if (giartifactsUuid == null) {
setGroupInstanceArtifactsUuid(new ArrayList<>());
}
}
/**
* Aligns the list of artifacts UUIDs of group instance according to received deployment artifacts
+ *
* @param deploymentArtifacts
*/
public void alignArtifactsUuid(Map<String, ArtifactDefinition> deploymentArtifacts) {
List<String> artifactIds = getArtifacts();
log.debug("the artifacts Id's are: {}, and the deployment artifacts Id's are: {}", artifactIds, deploymentArtifacts);
- if(CollectionUtils.isNotEmpty(artifactIds) && deploymentArtifacts != null){
+ if (CollectionUtils.isNotEmpty(artifactIds) && deploymentArtifacts != null) {
removeArtifactsDuplicates();
clearArtifactsUuid();
List<String> artifactUuids = getArtifactsUuid();
List<String> giArtifactUuids = getGroupInstanceArtifactsUuid();
- for(String artifactId : artifactIds){
+ for (String artifactId : artifactIds) {
String label = artifactId.substring(artifactId.lastIndexOf('.') + 1);
ArtifactDefinition artifact = deploymentArtifacts.get(label);
log.debug("current artifact id: {}, current artifact definition: {}", artifactId, artifact);
ArtifactTypeEnum artifactType = ArtifactTypeEnum.parse(artifact.getArtifactType());
- if (artifactType != ArtifactTypeEnum.HEAT_ENV){
+ if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
addArtifactsIdToCollection(artifactUuids, artifact);
- }else{
+ } else {
addArtifactsIdToCollection(giArtifactUuids, artifact);
}
}
-
}
}
private void addArtifactsIdToCollection(List<String> artifactUuids, ArtifactDefinition artifact) {
- if(!artifactUuids.contains(artifact.getArtifactUUID()) && StringUtils.isNotEmpty(artifact.getArtifactUUID())){
+ if (!artifactUuids.contains(artifact.getArtifactUUID()) && StringUtils.isNotEmpty(artifact.getArtifactUUID())) {
artifactUuids.add(artifact.getArtifactUUID());
-
}
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstanceProperty.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstanceProperty.java
index 55b3345a3b..386cfd2021 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstanceProperty.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstanceProperty.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
@@ -54,6 +53,4 @@ public class GroupInstanceProperty extends GroupProperty {
public void setParentValue(String parentValue) {
this.parentValue = parentValue;
}
-
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java
index 95702a3486..829da891a0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
@@ -25,8 +24,7 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
public class GroupProperty extends PropertyDefinition {
/**
- * The unique is of Group property on graph. If it is null, then the
- * property's value was not updated. The value is taken from the group type
+ * The unique is of Group property on graph. If it is null, then the property's value was not updated. The value is taken from the group type
* property.
*/
private String valueUniqueUid;
@@ -48,6 +46,7 @@ public class GroupProperty extends PropertyDefinition {
this.valueUniqueUid = other.getValueUniqueUid();
}
}
+
public GroupProperty(PropertyDataDefinition other) {
super(other);
}
@@ -62,7 +61,6 @@ public class GroupProperty extends PropertyDefinition {
@Override
public String toString() {
- return "GroupProperty [ " + super.toString() + ", valueUniqueUid = " + valueUniqueUid
- + " ]";
+ return "GroupProperty [ " + super.toString() + ", valueUniqueUid = " + valueUniqueUid + " ]";
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupTypeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupTypeDefinition.java
index ec1c334bb5..f3fb9f7829 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupTypeDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupTypeDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
-import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition;
-
import java.util.List;
import java.util.Map;
+import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition;
/**
* Specifies the group type that the Node Type exposes.
@@ -31,15 +29,7 @@ import java.util.Map;
public class GroupTypeDefinition extends GroupTypeDataDefinition {
private List<PropertyDefinition> properties;
- private Map<String, CapabilityDefinition> capabilities;
-
- public List<PropertyDefinition> getProperties() {
- return properties;
- }
-
- public void setProperties(List<PropertyDefinition> properties) {
- this.properties = properties;
- }
+ private Map<String, CapabilityDefinition> capabilities;
public GroupTypeDefinition() {
super();
@@ -49,11 +39,19 @@ public class GroupTypeDefinition extends GroupTypeDataDefinition {
super(p);
}
- public Map<String, CapabilityDefinition> getCapabilities() {
+ public List<PropertyDefinition> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(List<PropertyDefinition> properties) {
+ this.properties = properties;
+ }
+
+ public Map<String, CapabilityDefinition> getCapabilities() {
return capabilities;
}
- public void setCapabilities(Map<String, CapabilityDefinition> capabilies) {
+ public void setCapabilities(Map<String, CapabilityDefinition> capabilies) {
this.capabilities = capabilies;
}
@@ -61,5 +59,4 @@ public class GroupTypeDefinition extends GroupTypeDataDefinition {
public String toString() {
return super.toString() + " [properties=" + properties + ", capabilities=" + capabilities + "]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/HeatParameterDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/HeatParameterDefinition.java
index 3f5c7b6d50..490dbb6c82 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/HeatParameterDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/HeatParameterDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeOutputCommon.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeOutputCommon.java
index b2241ca905..e6318ceeb2 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeOutputCommon.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeOutputCommon.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.List;
@@ -27,7 +26,10 @@ import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
public interface IAttributeOutputCommon {
String getType();
+
ToscaDataDefinition getSchema();
+
List<PropertyRule> getRules();
+
String getName();
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IComplexDefaultValue.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IComplexDefaultValue.java
index bc3fe50d08..426d1346ee 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IComplexDefaultValue.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IComplexDefaultValue.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
public interface IComplexDefaultValue {
+
String getType();
String getName();
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IComponentInstanceConnectedElement.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IComponentInstanceConnectedElement.java
index 3de05c3fb8..11946c3731 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IComponentInstanceConnectedElement.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IComponentInstanceConnectedElement.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
public interface IComponentInstanceConnectedElement {
+
String getUniqueId();
String getValueUniqueUid();
@@ -28,7 +28,10 @@ public interface IComponentInstanceConnectedElement {
void setValueUniqueUid(String value);
String getComponentInstanceName();
+
void setComponentInstanceName(String componentInstanceName);
+
String getComponentInstanceId();
+
void setComponentInstanceId(String componentInstanceId);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IOperationParameter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IOperationParameter.java
index 6fbad2061e..3db3f9ad93 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IOperationParameter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IOperationParameter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
/**
- * An operation parameter can be either a PropertyValue (value or expression) or
- * a PropertyDefinition.
+ * An operation parameter can be either a PropertyValue (value or expression) or a PropertyDefinition.
*/
public interface IOperationParameter {
+
/**
- * Allow to know if the operation parameter is a property definition or a
- * property value. Only parameter exposed as property definitions can be
+ * Allow to know if the operation parameter is a property definition or a property value. Only parameter exposed as property definitions can be
* used for "custom" operations.
*
- * @return true if the operation parameter is a property definition and
- * false if the parameter is a property value.
+ * @return true if the operation parameter is a property definition and false if the parameter is a property value.
*/
boolean isDefinition();
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java
index 32a6fdf6f8..9cf04f4796 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
+import java.util.List;
import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
-import java.util.List;
-
public interface IPropertyInputCommon {
String getType();
+
SchemaDefinition getSchema();
+
List<PropertyRule> getRules();
+
String getName();
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java
index bbb71463fc..3d08bcb1f0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
import lombok.Getter;
import lombok.Setter;
import org.openecomp.sdc.be.datatypes.elements.Annotation;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
@Getter
@Setter
public class InputDefinition extends PropertyDefinition {
@@ -52,8 +50,7 @@ public class InputDefinition extends PropertyDefinition {
super(other);
}
- public void setAnnotationsToInput(Collection<Annotation> annotations){
+ public void setAnnotationsToInput(Collection<Annotation> annotations) {
this.setAnnotations(new ArrayList<>(annotations));
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java
index 204d484937..f4b0e8e522 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -28,8 +27,7 @@ import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
/**
- * Definition of the operations that can be performed on (instances of) a Node
- * Type.
+ * Definition of the operations that can be performed on (instances of) a Node Type.
*
* @author esofer
*/
@@ -55,10 +53,7 @@ public class InterfaceDefinition extends InterfaceDataDefinition implements IOpe
@JsonIgnore
public Map<String, Operation> getOperationsMap() {
- return getOperations().entrySet()
- .stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> new Operation(e
- .getValue())));
+ return getOperations().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new Operation(e.getValue())));
}
@JsonIgnore
@@ -66,14 +61,14 @@ public class InterfaceDefinition extends InterfaceDataDefinition implements IOpe
if (MapUtils.isEmpty(operations)) {
return;
}
- final Map<String, OperationDataDefinition> convertedOperation = operations.entrySet()
- .stream()
+ final Map<String, OperationDataDefinition> convertedOperation = operations.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> new OperationDataDefinition(e.getValue())));
setOperations(convertedOperation);
}
/**
* Checks if the interface has the given operation
+ *
* @param operation the operation to check
* @return {@code true} if the operation exists, {@code false} otherwise
*/
@@ -82,8 +77,6 @@ public class InterfaceDefinition extends InterfaceDataDefinition implements IOpe
if (MapUtils.isEmpty(operationMap)) {
return false;
}
- return operationMap.keySet().stream()
- .anyMatch(operation1 -> operation1.equalsIgnoreCase(operation));
+ return operationMap.keySet().stream().anyMatch(operation1 -> operation1.equalsIgnoreCase(operation));
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifeCycleTransitionEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifeCycleTransitionEnum.java
index 365e65f8a1..ff43297a2a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifeCycleTransitionEnum.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifeCycleTransitionEnum.java
@@ -17,11 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
public enum LifeCycleTransitionEnum {
-
+ // @formatter:off
CHECKOUT("checkout"),
CHECKIN("checkin"),
CERTIFICATION_REQUEST("certificationRequest"),
@@ -31,6 +30,7 @@ public enum LifeCycleTransitionEnum {
FAIL_CERTIFICATION("failCertification"),
CERTIFY("certify"),
DISTRIBUTE("distribute");
+ // @formatter:on
String displayName;
@@ -38,10 +38,6 @@ public enum LifeCycleTransitionEnum {
this.displayName = displayName;
}
- public String getDisplayName() {
- return displayName;
- }
-
public static LifeCycleTransitionEnum getFromDisplayName(final String name) {
if (name.equalsIgnoreCase(CHECKOUT.getDisplayName())) {
return CHECKOUT;
@@ -81,4 +77,8 @@ public enum LifeCycleTransitionEnum {
}
return sb.toString();
}
+
+ public String getDisplayName() {
+ return displayName;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifecycleStateEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifecycleStateEnum.java
index 8156ea20c9..5bcca4042d 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifecycleStateEnum.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifecycleStateEnum.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
public enum LifecycleStateEnum {
-
- CERTIFIED,
-
- NOT_CERTIFIED_CHECKIN,
-
- NOT_CERTIFIED_CHECKOUT;
+ CERTIFIED, NOT_CERTIFIED_CHECKIN, NOT_CERTIFIED_CHECKOUT;
public static LifecycleStateEnum findState(String state) {
-
for (LifecycleStateEnum lifecycleStateEnum : LifecycleStateEnum.values()) {
if (lifecycleStateEnum.name().equals(state)) {
return lifecycleStateEnum;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/MapInterfaceDataDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/MapInterfaceDataDefinition.java
index 4d25ad3743..c83469f478 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/MapInterfaceDataDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/MapInterfaceDataDefinition.java
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.model;
import com.fasterxml.jackson.annotation.JsonCreator;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/MapInterfaceInstanceDataDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/MapInterfaceInstanceDataDefinition.java
index 47db902319..2387cb73b8 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/MapInterfaceInstanceDataDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/MapInterfaceInstanceDataDefinition.java
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.model;
import com.fasterxml.jackson.annotation.JsonCreator;
@@ -22,8 +21,7 @@ import java.util.Map;
import org.openecomp.sdc.be.datatypes.elements.InterfaceInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
-public class MapInterfaceInstanceDataDefinition extends
- MapDataDefinition<InterfaceInstanceDataDefinition> {
+public class MapInterfaceInstanceDataDefinition extends MapDataDefinition<InterfaceInstanceDataDefinition> {
@JsonCreator
public MapInterfaceInstanceDataDefinition(Map<String, InterfaceInstanceDataDefinition> mapToscaDataDefinition) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java
index 1296129859..3bb33233f7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import java.util.List;
import java.util.Map;
public class NodeTypeInfo {
+
String type;
String templateFileName;
List<String> derivedFrom;
@@ -31,7 +31,7 @@ public class NodeTypeInfo {
boolean isSubstitutionMapping;
Map<String, Object> mappedToscaTemplate;
- public NodeTypeInfo getUnmarkedCopy(){
+ public NodeTypeInfo getUnmarkedCopy() {
NodeTypeInfo unmarked = new NodeTypeInfo();
unmarked.type = this.type;
unmarked.templateFileName = this.templateFileName;
@@ -45,30 +45,39 @@ public class NodeTypeInfo {
public String getType() {
return type;
}
+
public void setType(String type) {
this.type = type;
}
+
public String getTemplateFileName() {
return templateFileName;
}
+
public void setTemplateFileName(String templateFileName) {
this.templateFileName = templateFileName;
}
+
public List<String> getDerivedFrom() {
return derivedFrom;
}
+
public void setDerivedFrom(List<String> derivedFrom) {
this.derivedFrom = derivedFrom;
}
+
public boolean isNested() {
return isNested;
}
+
public void setNested(boolean isNested) {
this.isNested = isNested;
}
+
public boolean isSubstitutionMapping() {
return isSubstitutionMapping;
}
+
public void setSubstitutionMapping(boolean isSubstitutionMapping) {
this.isSubstitutionMapping = isSubstitutionMapping;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java
index a2fe8b2137..180f82cfff 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
@@ -28,23 +27,19 @@ import org.openecomp.sdc.be.datatypes.elements.OperationOutputDefinition;
/**
* Defines an operation available to manage particular aspects of the Node Type.
- *
+ *
* @author esofer
*/
public class Operation extends OperationDataDefinition implements IOperationParameter {
-
-
private boolean definition;
/**
* <p>
- * Jackson DeSerialization workaround constructor to create an operation
- * with no arguments.
+ * Jackson DeSerialization workaround constructor to create an operation with no arguments.
* </p>
*
- * @param emptyString
- * The empty string provided by jackson.
+ * @param emptyString The empty string provided by jackson.
*/
public Operation() {
super();
@@ -54,13 +49,12 @@ public class Operation extends OperationDataDefinition implements IOperationPara
super(p);
}
- public Operation(ArtifactDataDefinition implementation, String description,
- ListDataDefinition<OperationInputDefinition> inputs,
- ListDataDefinition<OperationOutputDefinition> outputs) {
+ public Operation(ArtifactDataDefinition implementation, String description, ListDataDefinition<OperationInputDefinition> inputs,
+ ListDataDefinition<OperationOutputDefinition> outputs) {
super(description);
setImplementation(implementation);
setInputs(inputs);
- setOutputs(outputs);
+ setOutputs(outputs);
}
@Override
@@ -77,8 +71,8 @@ public class Operation extends OperationDataDefinition implements IOperationPara
return "Operation [definition=" + definition + "]";
}
- public ArtifactDefinition getImplementationArtifact(){
- if ( getImplementation() != null ){
+ public ArtifactDefinition getImplementationArtifact() {
+ if (getImplementation() != null) {
return new ArtifactDefinition(getImplementation());
}
return null;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/OperationInput.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/OperationInput.java
index e11bf9620b..cbe836a5d3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/OperationInput.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/OperationInput.java
@@ -16,10 +16,10 @@
package org.openecomp.sdc.be.model;
import java.util.List;
-
import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition;
public class OperationInput extends OperationInputDefinition {
+
private List<PropertyConstraint> constraints;
public OperationInput(OperationInputDefinition operationInputDefinition) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/OperationInstance.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/OperationInstance.java
index fb958eb7b6..8a3f83f3ee 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/OperationInstance.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/OperationInstance.java
@@ -13,51 +13,51 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.model;
-import org.openecomp.sdc.be.datatypes.elements.OperationImplementation;
-
import java.util.Map;
import java.util.Objects;
+import org.openecomp.sdc.be.datatypes.elements.OperationImplementation;
public class OperationInstance/* extends Operation*/ {
- private OperationImplementation implementation;
- private Map<String, Object> inputs;
+ private OperationImplementation implementation;
+ private Map<String, Object> inputs;
- public OperationImplementation getImplementation() {
- return implementation;
- }
- public void setImplementation(OperationImplementation implementation) {
- this.implementation = implementation;
- }
+ public OperationImplementation getImplementation() {
+ return implementation;
+ }
- public Map<String, Object> getInputs() {
- return inputs;
- }
+ public void setImplementation(OperationImplementation implementation) {
+ this.implementation = implementation;
+ }
- public void setInputs(Map<String, Object> inputs) {
- this.inputs = inputs;
- }
+ public Map<String, Object> getInputs() {
+ return inputs;
+ }
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
+ public void setInputs(Map<String, Object> inputs) {
+ this.inputs = inputs;
}
- if (!(o instanceof OperationInstance)) {
- return false;
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof OperationInstance)) {
+ return false;
+ }
+ OperationInstance that = (OperationInstance) o;
+ return Objects.equals(implementation, that.implementation) &&
+ Objects.equals(inputs, that.inputs);
}
- OperationInstance that = (OperationInstance) o;
- return Objects.equals(implementation, that.implementation) &&
- Objects.equals(inputs, that.inputs);
- }
- @Override
- public int hashCode() {
+ @Override
+ public int hashCode() {
- return Objects.hash(implementation, inputs);
- }
+ return Objects.hash(implementation, inputs);
+ }
}
+
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/OutputDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/OutputDefinition.java
index 354a5b2ae3..3d2125471d 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/OutputDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/OutputDefinition.java
@@ -16,7 +16,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.List;
@@ -29,6 +28,7 @@ import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
@Setter
@NoArgsConstructor
public class OutputDefinition extends AttributeDefinition {
+
private List<ComponentInstanceAttribute> attributes;
public OutputDefinition(final AttributeDataDefinition attributeDataDefinition) {
@@ -42,5 +42,4 @@ public class OutputDefinition extends AttributeDefinition {
public OutputDefinition(final OutputDefinition outputDefinition) {
super(outputDefinition);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ParsedToscaYamlInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ParsedToscaYamlInfo.java
index a6f4165aeb..a8de860b28 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ParsedToscaYamlInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ParsedToscaYamlInfo.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import java.util.Map;
@@ -29,6 +28,7 @@ import lombok.ToString;
@Getter
@Setter
public class ParsedToscaYamlInfo {
+
Map<String, InputDefinition> inputs;
Map<String, UploadComponentInstanceInfo> instances;
Map<String, GroupDefinition> groups;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Point.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Point.java
index a8bf79755f..3e62838cf5 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Point.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Point.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
public class Point {
@@ -55,5 +54,4 @@ public class Point {
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyDefinition.java
index 65aa88c599..5b8a71082a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import java.util.HashMap;
@@ -26,6 +25,7 @@ import java.util.stream.Collectors;
import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+
/**
* public class representing the component policy
*/
@@ -44,6 +44,7 @@ public class PolicyDefinition extends PolicyDataDefinition implements Properties
/**
* public constructor from superclass
+ *
* @param policy
*/
public PolicyDefinition(Map<String, Object> policy) {
@@ -52,6 +53,7 @@ public class PolicyDefinition extends PolicyDataDefinition implements Properties
/**
* public copy constructor
+ *
* @param other
*/
public PolicyDefinition(PolicyDataDefinition other) {
@@ -59,8 +61,8 @@ public class PolicyDefinition extends PolicyDataDefinition implements Properties
}
/**
- * public converter constructor
- * builds PolicyDefinition object based on received PolicyTypeDefinition object
+ * public converter constructor builds PolicyDefinition object based on received PolicyTypeDefinition object
+ *
* @param policyType
*/
public PolicyDefinition(PolicyTypeDefinition policyType) {
@@ -73,7 +75,6 @@ public class PolicyDefinition extends PolicyDataDefinition implements Properties
this.setProperties(policyType.getProperties().stream().map(PropertyDataDefinition::new).collect(Collectors.toList()));
}
this.setTargets(new HashMap<>());
-
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTargetDTO.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTargetDTO.java
index 4d76391e3f..1fe447db58 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTargetDTO.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTargetDTO.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.List;
public class PolicyTargetDTO {
-
private String type;
private List<String> uniqueIds;
@@ -43,9 +41,4 @@ public class PolicyTargetDTO {
public void setUniqueIds(List<String> ids) {
this.uniqueIds = ids;
}
-
-
-
-
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTypeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTypeDefinition.java
index 0cfdf196e1..3f3577664e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTypeDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTypeDefinition.java
@@ -17,12 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
-import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition;
-
import java.util.List;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition;
/**
* Specifies the policy type that the Node Type exposes.
@@ -31,14 +29,6 @@ public class PolicyTypeDefinition extends PolicyTypeDataDefinition {
private List<PropertyDefinition> properties;
- public List<PropertyDefinition> getProperties() {
- return properties;
- }
-
- public void setProperties(List<PropertyDefinition> properties) {
- this.properties = properties;
- }
-
public PolicyTypeDefinition() {
super();
}
@@ -47,6 +37,14 @@ public class PolicyTypeDefinition extends PolicyTypeDataDefinition {
super(p);
}
+ public List<PropertyDefinition> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(List<PropertyDefinition> properties) {
+ this.properties = properties;
+ }
+
@Override
public String toString() {
return super.toString() + " [ properties=" + properties + " ]";
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java
index b08df77922..c758cbcad3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.List;
@@ -77,5 +76,4 @@ public class Product extends Component {
private ProductMetadataDataDefinition getProductMetadataDefinition() {
return (ProductMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition();
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ProductMetadataDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ProductMetadataDefinition.java
index 71d54d90d2..cc4856380a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ProductMetadataDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ProductMetadataDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import org.openecomp.sdc.be.datatypes.elements.ProductMetadataDataDefinition;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyConstraint.java
index 3ed1e37c6f..6bc8083118 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -42,5 +41,4 @@ public interface PropertyConstraint {
void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException;
String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException exception, String propertyName);
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java
index d25cb72d64..c06df6541f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,98 +17,21 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
+import static org.openecomp.sdc.be.dao.utils.CollectionUtils.safeGetList;
+
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
-import org.apache.commons.collections.CollectionUtils;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-
import java.lang.reflect.Type;
import java.util.List;
import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import static org.openecomp.sdc.be.dao.utils.CollectionUtils.safeGetList;
-
-
-
-public class PropertyDefinition extends PropertyDataDefinition
- implements IOperationParameter, IComplexDefaultValue {
-
-
- /**The enumeration presents the list of property names with specific behavior
- * @author rbetzer
- *
- */
- public enum PropertyNames {
-
- MIN_INSTANCES("min_vf_module_instances", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
- MAX_INSTANCES("max_vf_module_instances", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
- INITIAL_COUNT("initial_count", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
- VF_MODULE_LABEL("vf_module_label", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_RESOURCE_LEVEL),
- VF_MODULE_DESCRIPTION("vf_module_description", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_RESOURCE_LEVEL),
- NETWORK_ROLE("network_role", GroupInstancePropertyValueUpdateBehavior.NOT_RELEVANT),
- AVAILABILTY_ZONE_COUNT("availability_zone_count", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
- VFC_LIST("vfc_list", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL);
-
- private String propertyName;
- private GroupInstancePropertyValueUpdateBehavior updateBehavior;
-
- PropertyNames(String propertyName,GroupInstancePropertyValueUpdateBehavior updateBehavior){
- this.propertyName = propertyName;
- this.updateBehavior = updateBehavior;
- }
-
- public String getPropertyName() {
- return propertyName;
- }
-
- public GroupInstancePropertyValueUpdateBehavior getUpdateBehavior() {
- return updateBehavior;
- }
- /**
- * finds PropertyNames according received string name
- * @param name of the property
- * @return PropertyNames found by received property name
- */
- public static PropertyNames findName(String name){
- for (PropertyNames e : PropertyNames.values()) {
- if (e.getPropertyName().equals(name)) {
- return e;
- }
- }
- return null;
- }
- }
- /**
- * The enumeration presents the list of highest levels for which update property value is allowed
- * @author nsheshukov
- *
- */
- public enum GroupInstancePropertyValueUpdateBehavior{
- NOT_RELEVANT("NOT_RELEVANT", -1),
- UPDATABLE_ON_RESOURCE_LEVEL("UPDATABLE_ON_VF_LEVEL", 0),
- UPDATABLE_ON_SERVICE_LEVEL("UPDATABLE_ON_SERVICE_LEVEL", 1);
-
- String levelName;
- int levelNumber;
-
- GroupInstancePropertyValueUpdateBehavior(String name, int levelNumber){
- this.levelName = name;
- this.levelNumber = levelNumber;
- }
-
- public String getLevelName() {
- return levelName;
- }
-
- public int getLevelNumber() {
- return levelNumber;
- }
- }
+public class PropertyDefinition extends PropertyDataDefinition implements IOperationParameter, IComplexDefaultValue {
private List<PropertyConstraint> constraints;
@@ -127,33 +50,33 @@ public class PropertyDefinition extends PropertyDataDefinition
}
public List<PropertyConstraint> getConstraints() {
- if(CollectionUtils.isEmpty(constraints)){
+ if (CollectionUtils.isEmpty(constraints)) {
constraints = deserializePropertyConstraints(findConstraints());
}
return constraints;
}
- public List<PropertyConstraint> safeGetConstraints() {
- return safeGetList(constraints);
- }
-
public void setConstraints(List<PropertyConstraint> constraints) {
setPropertyConstraints(serializePropertyConstraints(constraints));
this.constraints = constraints;
}
+ public List<PropertyConstraint> safeGetConstraints() {
+ return safeGetList(constraints);
+ }
+
private List<PropertyConstraint> deserializePropertyConstraints(List<String> constraints) {
- if(CollectionUtils.isNotEmpty(constraints)){
+ if (CollectionUtils.isNotEmpty(constraints)) {
Type constraintType = new TypeToken<PropertyConstraint>() {
}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyOperation.PropertyConstraintDeserialiser()).create();
- return constraints.stream().map(c -> (PropertyConstraint)gson.fromJson(c, constraintType)).collect(Collectors.toList());
+ return constraints.stream().map(c -> (PropertyConstraint) gson.fromJson(c, constraintType)).collect(Collectors.toList());
}
return null;
}
private List<String> serializePropertyConstraints(List<PropertyConstraint> constraints) {
- if(CollectionUtils.isNotEmpty(constraints)){
+ if (CollectionUtils.isNotEmpty(constraints)) {
Type constraintType = new TypeToken<PropertyConstraint>() {
}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyOperation.PropertyConstraintSerialiser()).create();
@@ -163,10 +86,10 @@ public class PropertyDefinition extends PropertyDataDefinition
}
private List<String> findConstraints() {
- if(CollectionUtils.isNotEmpty(getPropertyConstraints())){
+ if (CollectionUtils.isNotEmpty(getPropertyConstraints())) {
return getPropertyConstraints();
}
- if(getSchemaProperty()!= null){
+ if (getSchemaProperty() != null) {
return getSchemaProperty().getPropertyConstraints();
}
return null;
@@ -174,8 +97,7 @@ public class PropertyDefinition extends PropertyDataDefinition
@Override
public String toString() {
- return "PropertyDefinition [ " + super.toString() + ", name=" + getName() + ", constraints="
- + constraints + "]]";
+ return "PropertyDefinition [ " + super.toString() + ", name=" + getName() + ", constraints=" + constraints + "]]";
}
@Override
@@ -194,24 +116,104 @@ public class PropertyDefinition extends PropertyDataDefinition
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (!super.equals(obj))
+ }
+ if (!super.equals(obj)) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
PropertyDefinition other = (PropertyDefinition) obj;
if (constraints == null) {
- if (other.constraints != null)
+ if (other.constraints != null) {
return false;
- } else if (!constraints.equals(other.constraints))
+ }
+ } else if (!constraints.equals(other.constraints)) {
return false;
+ }
if (getName() == null) {
- if (other.getName() != null)
+ if (other.getName() != null) {
return false;
- } else if (!getName().equals(other.getName()))
+ }
+ } else if (!getName().equals(other.getName())) {
return false;
+ }
return true;
}
+ /**
+ * The enumeration presents the list of property names with specific behavior
+ *
+ * @author rbetzer
+ */
+ public enum PropertyNames {
+ // @formatter:off
+ MIN_INSTANCES("min_vf_module_instances", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
+ MAX_INSTANCES("max_vf_module_instances", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
+ INITIAL_COUNT("initial_count", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
+ VF_MODULE_LABEL("vf_module_label", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_RESOURCE_LEVEL),
+ VF_MODULE_DESCRIPTION("vf_module_description", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_RESOURCE_LEVEL),
+ NETWORK_ROLE("network_role", GroupInstancePropertyValueUpdateBehavior.NOT_RELEVANT),
+ AVAILABILTY_ZONE_COUNT("availability_zone_count", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL),
+ VFC_LIST("vfc_list", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL);
+ // @formatter:on
+
+ private String propertyName;
+ private GroupInstancePropertyValueUpdateBehavior updateBehavior;
+
+ PropertyNames(String propertyName, GroupInstancePropertyValueUpdateBehavior updateBehavior) {
+ this.propertyName = propertyName;
+ this.updateBehavior = updateBehavior;
+ }
+
+ /**
+ * finds PropertyNames according received string name
+ *
+ * @param name of the property
+ * @return PropertyNames found by received property name
+ */
+ public static PropertyNames findName(String name) {
+ for (PropertyNames e : PropertyNames.values()) {
+ if (e.getPropertyName().equals(name)) {
+ return e;
+ }
+ }
+ return null;
+ }
+
+ public String getPropertyName() {
+ return propertyName;
+ }
+
+ public GroupInstancePropertyValueUpdateBehavior getUpdateBehavior() {
+ return updateBehavior;
+ }
+ }
+
+ /**
+ * The enumeration presents the list of highest levels for which update property value is allowed
+ *
+ * @author nsheshukov
+ */
+ public enum GroupInstancePropertyValueUpdateBehavior {
+ NOT_RELEVANT("NOT_RELEVANT", -1), UPDATABLE_ON_RESOURCE_LEVEL("UPDATABLE_ON_VF_LEVEL", 0), UPDATABLE_ON_SERVICE_LEVEL(
+ "UPDATABLE_ON_SERVICE_LEVEL", 1);
+ String levelName;
+ int levelNumber;
+
+ GroupInstancePropertyValueUpdateBehavior(String name, int levelNumber) {
+ this.levelName = name;
+ this.levelNumber = levelNumber;
+ }
+
+ public String getLevelName() {
+ return levelName;
+ }
+
+ public int getLevelNumber() {
+ return levelNumber;
+ }
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyScope.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyScope.java
index cd94f2fce8..da02ec6f79 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyScope.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyScope.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
public class PropertyScope {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipImpl.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipImpl.java
index 0d0702723f..0a6af323f3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipImpl.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipImpl.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
public class RelationshipImpl {
@@ -36,5 +35,4 @@ public class RelationshipImpl {
public String toString() {
return "RelationshipImpl [type=" + type + "]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipInfo.java
index f67d8bb729..066cfbbec4 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipInfo.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition;
@@ -28,11 +27,8 @@ public class RelationshipInfo {
private String capabilityOwnerId;
private String requirementOwnerId;
private String id;
-
private RelationshipImpl relationship;
-
private String capability;
-
private String capabilityUid;
private String requirementUid;
@@ -119,37 +115,35 @@ public class RelationshipInfo {
@Override
public String toString() {
- return "RequirementAndRelationshipPair [requirement=" + requirement + ", relationship=" + relationship
- + ", capability=" + capability + "]";
+ return "RequirementAndRelationshipPair [requirement=" + requirement + ", relationship=" + relationship + ", capability=" + capability + "]";
}
- public boolean equalsTo( RelationshipInstDataDefinition savedRelation){
- if ( savedRelation == null ){
+ public boolean equalsTo(RelationshipInstDataDefinition savedRelation) {
+ if (savedRelation == null) {
return false;
}
- if(getRelationship().getType() == null ){
- if(savedRelation.getType() != null){
+ if (getRelationship().getType() == null) {
+ if (savedRelation.getType() != null) {
return false;
}
- }
- else {
- if ( !savedRelation.getType().equals(this.getRelationship().getType()) ){
+ } else {
+ if (!savedRelation.getType().equals(this.getRelationship().getType())) {
return false;
}
}
- if ( !savedRelation.getCapabilityOwnerId().equals(this.getCapabilityOwnerId()) ){
+ if (!savedRelation.getCapabilityOwnerId().equals(this.getCapabilityOwnerId())) {
return false;
}
- if ( !savedRelation.getRequirementOwnerId().equals(this.getRequirementOwnerId()) ){
+ if (!savedRelation.getRequirementOwnerId().equals(this.getRequirementOwnerId())) {
return false;
}
- if ( !savedRelation.getRequirementId().equals(this.getRequirementUid()) ){
+ if (!savedRelation.getRequirementId().equals(this.getRequirementUid())) {
return false;
}
- if ( !savedRelation.getCapabilityId().equals(this.getCapabilityUid()) ){
+ if (!savedRelation.getCapabilityId().equals(this.getCapabilityUid())) {
return false;
}
- if ( !savedRelation.getRequirement().equals(this.getRequirement()) ){
+ if (!savedRelation.getRequirement().equals(this.getRequirement())) {
return false;
}
return true;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipTypeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipTypeDefinition.java
index 5b03d0ce1b..fd988fa565 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipTypeDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RelationshipTypeDefinition.java
@@ -13,22 +13,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-
package org.openecomp.sdc.be.model;
+import java.util.Map;
import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition;
import org.openecomp.sdc.be.resources.data.RelationshipTypeData;
-import java.util.Map;
-
/**
* Specifies the capabilities that the Node Type exposes.
*/
public class RelationshipTypeDefinition extends RelationshipInstDataDefinition {
private String derivedFrom;
-
private Map<String, PropertyDefinition> properties;
public RelationshipTypeDefinition() {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementCapabilityRelDef.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementCapabilityRelDef.java
index 1c14293a13..678b0f9d53 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementCapabilityRelDef.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementCapabilityRelDef.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import lombok.Getter;
@@ -37,9 +36,7 @@ public class RequirementCapabilityRelDef extends TargetCapabilityRelDef {
public RequirementCapabilityRelDef(RequirementCapabilityRelDef another) {
super(another.getToNode(), another.getRelationships());
-
fromNode = another.getFromNode();
originUI = another.isOriginUI();
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java
index acc7452ab4..e5b4134ae2 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementImplDef.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementImplDef.java
index bf394fd187..21a211ac5c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementImplDef.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementImplDef.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import java.util.Map;
@@ -25,14 +24,11 @@ import java.util.Map;
public class RequirementImplDef {
private String uniqueId;
-
/**
* node type(mandatory). Unique id of the node we choose.
*/
private String nodeId;
-
private Map<String, CapabiltyInstance> requirementProperties;
-
private Point point;
public String getNodeId() {
@@ -69,8 +65,7 @@ public class RequirementImplDef {
@Override
public String toString() {
- return "RequirementImplDef [uniqueId=" + uniqueId + ", nodeId=" + nodeId + ", requirementProperties="
- + requirementProperties + ", point=" + point + "]";
+ return "RequirementImplDef [uniqueId=" + uniqueId + ", nodeId=" + nodeId + ", requirementProperties=" + requirementProperties + ", point="
+ + point + "]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementInstance.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementInstance.java
index 0aa85344f9..a7218eb86c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementInstance.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementInstance.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
/**
@@ -29,7 +28,6 @@ public class RequirementInstance {
* specify the resource instance name as appears in the service
*/
private String node;
-
/**
* specify the relationship impl
*/
@@ -55,5 +53,4 @@ public class RequirementInstance {
public String toString() {
return "RequirementInstance [node=" + node + ", relationship=" + relationship + "]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java
index 0e4753c3f7..a75ed9f68b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.List;
@@ -41,19 +40,15 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
public class Resource extends Component {
/**
- * Please note that more than one "derivedFrom" resource is not currently supported by the app. The first list
- * element is always addressed.
+ * Please note that more than one "derivedFrom" resource is not currently supported by the app. The first list element is always addressed.
*/
private List<String> derivedFrom;
-
/**
- * The derivedList is a chain of derivedFrom. e.g. if resource C is derived from resource B that is derived from
- * resource A - then A, B is the "DerivedList" of resource C
+ * The derivedList is a chain of derivedFrom. e.g. if resource C is derived from resource B that is derived from resource A - then A, B is the
+ * "DerivedList" of resource C
*/
private List<String> derivedList;
-
private Map<String, String> derivedFromMapOfIdToName;
-
private String toscaVersion;
public Resource() {
@@ -64,25 +59,21 @@ public class Resource extends Component {
public Resource(ComponentMetadataDefinition componentMetadataDefinition) {
super(componentMetadataDefinition);
if (this.getComponentMetadataDefinition().getMetadataDataDefinition() == null) {
- this.getComponentMetadataDefinition().componentMetadataDataDefinition =
- new ResourceMetadataDataDefinition();
+ this.getComponentMetadataDefinition().componentMetadataDataDefinition = new ResourceMetadataDataDefinition();
}
this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.RESOURCE);
}
public Boolean isAbstract() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .isAbstract();
+ return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).isAbstract();
}
public void setAbstract(Boolean isAbstract) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .setAbstract(isAbstract);
+ ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setAbstract(isAbstract);
}
public String getCost() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .getCost();
+ return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getCost();
}
public void setCost(String cost) {
@@ -90,58 +81,47 @@ public class Resource extends Component {
}
public String getLicenseType() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .getLicenseType();
+ return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getLicenseType();
}
public void setLicenseType(String licenseType) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .setLicenseType(licenseType);
+ ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setLicenseType(licenseType);
}
public String getToscaResourceName() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .getToscaResourceName();
+ return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName();
}
public void setToscaResourceName(String toscaResourceName) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .setToscaResourceName(toscaResourceName);
+ ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setToscaResourceName(toscaResourceName);
}
public ResourceTypeEnum getResourceType() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .getResourceType();
+ return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
}
public void setResourceType(ResourceTypeEnum resourceType) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .setResourceType(resourceType);
+ ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setResourceType(resourceType);
}
public String getVendorName() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .getVendorName();
+ return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorName();
}
public void setVendorName(String vendorName) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .setVendorName(vendorName);
+ ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setVendorName(vendorName);
}
public String getVendorRelease() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .getVendorRelease();
+ return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease();
}
public void setVendorRelease(String vendorRelease) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .setVendorRelease(vendorRelease);
+ ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setVendorRelease(vendorRelease);
}
public String getResourceVendorModelNumber() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .getResourceVendorModelNumber();
+ return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceVendorModelNumber();
}
public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
@@ -164,16 +144,14 @@ public class Resource extends Component {
}
private Optional<String> fetchToscaNameFromConfigBasedOnCategory() {
- return getHeadOption(this.getCategories()).flatMap(category -> getHeadOption(category.getSubcategories()).map(
- subCategory -> fetchToscaNameFromConfigBasedOnCategory(category.getName(), subCategory.getName())));
+ return getHeadOption(this.getCategories()).flatMap(category -> getHeadOption(category.getSubcategories())
+ .map(subCategory -> fetchToscaNameFromConfigBasedOnCategory(category.getName(), subCategory.getName())));
}
- private String fetchToscaNameFromConfigBasedOnCategory(final String resourceCategory,
- final String resourceSubCategory) {
- return Optional
- .ofNullable(ConfigurationManager.getConfigurationManager().getConfiguration().getResourceNodeTypes())
- .map(categoryNames -> categoryNames.get(resourceCategory))
- .map(subCategoryNames -> subCategoryNames.get(resourceSubCategory)).orElse(null);
+ private String fetchToscaNameFromConfigBasedOnCategory(final String resourceCategory, final String resourceSubCategory) {
+ return Optional.ofNullable(ConfigurationManager.getConfigurationManager().getConfiguration().getResourceNodeTypes())
+ .map(categoryNames -> categoryNames.get(resourceCategory)).map(subCategoryNames -> subCategoryNames.get(resourceSubCategory))
+ .orElse(null);
}
@Override
@@ -188,22 +166,19 @@ public class Resource extends Component {
@Override
public boolean deriveFromGeneric() {
- return this.shouldGenerateInputs()
- || (derivedFrom != null && derivedFrom.contains(fetchGenericTypeToscaNameFromConfig()));
+ return this.shouldGenerateInputs() || (derivedFrom != null && derivedFrom.contains(fetchGenericTypeToscaNameFromConfig()));
}
public Map<String, List<RequirementCapabilityRelDef>> groupRelationsFromCsarByInstanceName(Resource resource) {
- List<RequirementCapabilityRelDef> componentInstanceRelationsFromCsar = resource.getComponentInstancesRelations()
- .stream().filter(r -> !r.isOriginUI()).collect(Collectors.toList());
- Map<String, List<RequirementCapabilityRelDef>> relationsByInstanceId =
- MapUtil.groupListBy(componentInstanceRelationsFromCsar, RequirementCapabilityRelDef::getFromNode);
- return MapUtil.convertMapKeys(relationsByInstanceId,
- instId -> getInstanceInvariantNameFromInstanceId(resource, instId));
+ List<RequirementCapabilityRelDef> componentInstanceRelationsFromCsar = resource.getComponentInstancesRelations().stream()
+ .filter(r -> !r.isOriginUI()).collect(Collectors.toList());
+ Map<String, List<RequirementCapabilityRelDef>> relationsByInstanceId = MapUtil
+ .groupListBy(componentInstanceRelationsFromCsar, RequirementCapabilityRelDef::getFromNode);
+ return MapUtil.convertMapKeys(relationsByInstanceId, instId -> getInstanceInvariantNameFromInstanceId(resource, instId));
}
private String getInstanceInvariantNameFromInstanceId(Resource resource, String instId) {
Optional<ComponentInstance> componentInstanceById = resource.getComponentInstanceById(instId);
return componentInstanceById.isPresent() ? componentInstanceById.get().getInvariantName() : null;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ResourceInstanceHeatParameter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ResourceInstanceHeatParameter.java
index 8c1f336b90..6c1a22c015 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ResourceInstanceHeatParameter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ResourceInstanceHeatParameter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
public class ResourceInstanceHeatParameter extends HeatParameterDefinition {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ResourceMetadataDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ResourceMetadataDefinition.java
index c049bdc39a..77779417f2 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ResourceMetadataDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ResourceMetadataDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
@@ -31,7 +30,5 @@ public class ResourceMetadataDefinition extends ComponentMetadataDefinition {
public ResourceMetadataDefinition(ResourceMetadataDataDefinition other) {
super(other);
-
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Schema.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Schema.java
index 794b775eee..7bd24766eb 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Schema.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Schema.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
/**
* Schema allows to create new types that can be used along TOSCA definitions.
*/
public class Schema {
+
private PropertyDefinition property;
public PropertyDefinition getProperty() {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java
index 2e326ce691..eedb5574f6 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java
@@ -17,13 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@@ -35,7 +33,6 @@ import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.InstantiationTypes;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum;
@Getter
@@ -56,8 +53,7 @@ public class Service extends Component {
public Service(ComponentMetadataDefinition serviceMetadataDefinition) {
super(serviceMetadataDefinition);
- ComponentMetadataDataDefinition metadataDataDefinition =
- this.getComponentMetadataDefinition().getMetadataDataDefinition();
+ ComponentMetadataDataDefinition metadataDataDefinition = this.getComponentMetadataDefinition().getMetadataDataDefinition();
if (metadataDataDefinition != null) {
metadataDataDefinition.setComponentType(ComponentTypeEnum.SERVICE);
}
@@ -164,15 +160,13 @@ public class Service extends Component {
@Override
public String fetchGenericTypeToscaNameFromConfig() {
- return getHeadOption(this.getCategories())
- .map(category -> fetchToscaNameFromConfigBasedOnService(category.getName()))
- .orElse(super.fetchGenericTypeToscaNameFromConfig());
+ return getHeadOption(this.getCategories()).map(category -> fetchToscaNameFromConfigBasedOnService(category.getName()))
+ .orElse(super.fetchGenericTypeToscaNameFromConfig());
}
private String fetchToscaNameFromConfigBasedOnService(final String serviceCategory) {
- return Optional
- .ofNullable(ConfigurationManager.getConfigurationManager().getConfiguration().getServiceNodeTypes())
- .map(serviceNames -> serviceNames.get(serviceCategory)).orElse(null);
+ return Optional.ofNullable(ConfigurationManager.getConfigurationManager().getConfiguration().getServiceNodeTypes())
+ .map(serviceNames -> serviceNames.get(serviceCategory)).orElse(null);
}
@Override
@@ -180,23 +174,19 @@ public class Service extends Component {
setServiceApiArtifacts(specificComponentTypeArtifacts);
}
-
public void setServiceVendorModelNumber(String serviceVendorModelNumber) {
getServiceMetadataDefinition().setServiceVendorModelNumber(serviceVendorModelNumber);
}
public void setAbstract(Boolean isAbstract) {
- ((ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .setIsAbstract(isAbstract);
+ ((ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setIsAbstract(isAbstract);
}
public void setVendorName(String vendorName) {
- ((ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .setVendorName(vendorName);
+ ((ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setVendorName(vendorName);
}
public void setVendorRelease(String vendorRelease) {
- ((ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
- .setVendorRelease(vendorRelease);
+ ((ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setVendorRelease(vendorRelease);
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ServiceMetadataDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ServiceMetadataDefinition.java
index 42111e0897..fec53c3903 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ServiceMetadataDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ServiceMetadataDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
@@ -32,5 +31,4 @@ public class ServiceMetadataDefinition extends ComponentMetadataDefinition {
public ServiceMetadataDefinition(ServiceMetadataDataDefinition component) {
super(component);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Tag.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Tag.java
index 045294eef0..3e7fce5b7f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Tag.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Tag.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
public class Tag {
@@ -61,5 +60,4 @@ public class Tag {
}
return true;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java
index 1237ade665..0ceba55205 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import java.util.List;
@@ -26,7 +25,6 @@ public class TargetCapabilityRelDef {
private String uid;
private String toNode;
-
private List<CapabilityRequirementRelationship> relationships;
public TargetCapabilityRelDef() {
@@ -50,6 +48,10 @@ public class TargetCapabilityRelDef {
return relationships;
}
+ public void setRelationships(List<CapabilityRequirementRelationship> relationships) {
+ this.relationships = relationships;
+ }
+
public CapabilityRequirementRelationship resolveSingleRelationship() {//currently only single relationship is supported
return relationships == null || relationships.isEmpty() ? null : relationships.get(0);
}
@@ -62,14 +64,8 @@ public class TargetCapabilityRelDef {
this.uid = uid;
}
- public void setRelationships(List<CapabilityRequirementRelationship> relationships) {
- this.relationships = relationships;
- }
-
@Override
public String toString() {
- return "TargetCapabilityRelDef [ toNode=" + toNode
- + ", relationships=" + relationships + "]";
+ return "TargetCapabilityRelDef [ toNode=" + toNode + ", relationships=" + relationships + "]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadArtifactInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadArtifactInfo.java
index bd07e36353..183f18c0b4 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadArtifactInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadArtifactInfo.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.List;
@@ -32,8 +31,6 @@ public class UploadArtifactInfo extends UploadInfo {
* specify the node type(Optional by tosca)
*/
private List<String> validSourceTypes;
-
private String file;
private String type;
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadCapInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadCapInfo.java
index 7d15799c82..82c1bdd8a7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadCapInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadCapInfo.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import java.util.List;
public class UploadCapInfo extends UploadInfo {
+
/**
* specify the node type(Optional by tosca)
*/
private List<String> validSourceTypes;
-
private List<UploadPropInfo> properties;
-
private String node;
public String getNode() {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java
index 8daf492a62..95649a94de 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import java.util.Collection;
import java.util.List;
import java.util.Map;
-
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class UploadComponentInstanceInfo {
+
private String name;
private String type;
private Map<String, List<UploadCapInfo>> capabilities;
@@ -40,5 +39,4 @@ public class UploadComponentInstanceInfo {
private Map<String, String> requirementsNamesToUpdate;
private Collection<String> directives;
private UploadNodeFilterInfo uploadNodeFilterInfo;
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadInfo.java
index d642737c6d..6b48e4fe2f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadInfo.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
public abstract class UploadInfo {
private String key;
-
private String type;
-
private String name;
public String getKey() {
@@ -51,5 +48,4 @@ public abstract class UploadInfo {
public void setName(String name) {
this.name = name;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadNodeFilterCapabilitiesInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadNodeFilterCapabilitiesInfo.java
index 4b14f9518d..5193cf22c0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadNodeFilterCapabilitiesInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadNodeFilterCapabilitiesInfo.java
@@ -25,5 +25,4 @@ public class UploadNodeFilterCapabilitiesInfo {
private String name;
private List<UploadNodeFilterPropertyInfo> properties;
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadNodeFilterInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadNodeFilterInfo.java
index 2b228d930c..b785222362 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadNodeFilterInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadNodeFilterInfo.java
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.model;
import java.util.ArrayList;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java
index 536e251b8b..d5221eeef2 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
-import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
-
import java.util.ArrayList;
import java.util.List;
-
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
public class UploadPropInfo extends UploadInfo {
private Object value;
-
private String description;
-
private boolean password;
-
private List<GetInputValueDataDefinition> get_input;
public List<GetInputValueDataDefinition> getGet_input() {
@@ -70,5 +64,4 @@ public class UploadPropInfo extends UploadInfo {
public void setPassword(boolean password) {
this.password = password;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadReqInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadReqInfo.java
index 47f8f1c195..a3f927925f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadReqInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadReqInfo.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
public class UploadReqInfo extends UploadInfo {
+
/**
* specify the node type(Optional by tosca)
*/
-
private String capabilityName;
-
private String node;
public String getCapabilityName() {
@@ -44,5 +42,4 @@ public class UploadReqInfo extends UploadInfo {
public void setNode(String node) {
this.node = node;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadResourceInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadResourceInfo.java
index ecc3403ab2..d6151c3d78 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadResourceInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadResourceInfo.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
+import java.util.ArrayList;
+import java.util.List;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.common.api.UploadArtifactInfo;
-import java.util.ArrayList;
-import java.util.List;
-
public class UploadResourceInfo {
private String payloadData;
@@ -34,14 +32,12 @@ public class UploadResourceInfo {
private String description;
private List<String> tags;
private List<CategoryDefinition> categories;
-
private List<UploadArtifactInfo> artifactList;
private String contactId, name, resourceIconPath, icon, vendorName, vendorRelease, resourceVendorModelNumber;
-
private String resourceType = "VFC";
- public UploadResourceInfo(String payload, String payloadName, String description, String category,
- List<String> tags, List<UploadArtifactInfo> artifactsList) {
+ public UploadResourceInfo(String payload, String payloadName, String description, String category, List<String> tags,
+ List<UploadArtifactInfo> artifactsList) {
super();
this.payloadData = payload;
this.payloadName = payloadName;
@@ -65,7 +61,6 @@ public class UploadResourceInfo {
public UploadResourceInfo() {
}
-
public String getPayloadData() {
return payloadData;
}
@@ -327,5 +322,4 @@ public class UploadResourceInfo {
}
}
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadServiceInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadServiceInfo.java
index 29d6fa40fd..1e5c8241c6 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadServiceInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadServiceInfo.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model;
import java.util.ArrayList;
@@ -32,113 +31,106 @@ import org.openecomp.sdc.common.api.UploadArtifactInfo;
@Setter
public class UploadServiceInfo {
- private String payloadData;
- private String payloadName;
- private String description;
- private List<String> tags;
- private List<CategoryDefinition> categories;
-
- private String invariantUUID;
- private String UUID;
- private String type;
- private String category;
- private String subcategory;
- private String resourceVendor;
- private String resourceVendorRelease;
- private String serviceRole;
- private String serviceEcompNaming;
- private String ecompGeneratedNaming;
- private String namingPolicy;
- private String projectCode;
-
-
- private List<UploadArtifactInfo> artifactList;
- private String contactId, name, serviceIconPath, icon, vendorName, vendorRelease, serviceVendorModelNumber;
+ private String payloadData;
+ private String payloadName;
+ private String description;
+ private List<String> tags;
+ private List<CategoryDefinition> categories;
+ private String invariantUUID;
+ private String UUID;
+ private String type;
+ private String category;
+ private String subcategory;
+ private String resourceVendor;
+ private String resourceVendorRelease;
+ private String serviceRole;
+ private String serviceEcompNaming;
+ private String ecompGeneratedNaming;
+ private String namingPolicy;
+ private String projectCode;
+ private List<UploadArtifactInfo> artifactList;
+ private String contactId, name, serviceIconPath, icon, vendorName, vendorRelease, serviceVendorModelNumber;
+ private String serviceType = "";
- private String serviceType = "";
-
- public UploadServiceInfo(String payloadData, String payloadName, String description,
- List<String> tags, String invariantUUID, String UUID, String type,
- String category, String subcategory, String resourceVendor,
- String resourceVendorRelease, String serviceRole, String serviceEcompNaming,
- String ecompGeneratedNaming, String namingPolicy,
- List<UploadArtifactInfo> artifactList, String contactId, String name,
- String resourceIconPath, String icon, String vendorName, String vendorRelease,
- String serviceVendorModelNumber, String serviceType, String projectCode) {
- this.payloadData = payloadData;
- this.payloadName = payloadName;
- this.description = description;
- this.tags = tags;
- this.invariantUUID = invariantUUID;
- this.UUID = UUID;
- this.type = type;
- this.category = category;
- this.subcategory = subcategory;
- this.resourceVendor = resourceVendor;
- this.resourceVendorRelease = resourceVendorRelease;
- this.serviceRole = serviceRole;
- this.serviceEcompNaming = serviceEcompNaming;
- this.ecompGeneratedNaming = ecompGeneratedNaming;
- this.namingPolicy = namingPolicy;
- this.artifactList = artifactList;
- this.contactId = contactId;
- this.name = name;
- this.serviceIconPath = serviceIconPath;
- this.icon = icon;
- this.vendorName = vendorName;
- this.vendorRelease = vendorRelease;
- this.serviceVendorModelNumber = serviceVendorModelNumber;
- this.serviceType = serviceType;
- this.projectCode = projectCode;
+ public UploadServiceInfo(String payloadData, String payloadName, String description, List<String> tags, String invariantUUID, String UUID,
+ String type, String category, String subcategory, String resourceVendor, String resourceVendorRelease,
+ String serviceRole, String serviceEcompNaming, String ecompGeneratedNaming, String namingPolicy,
+ List<UploadArtifactInfo> artifactList, String contactId, String name, String resourceIconPath, String icon,
+ String vendorName, String vendorRelease, String serviceVendorModelNumber, String serviceType, String projectCode) {
+ this.payloadData = payloadData;
+ this.payloadName = payloadName;
+ this.description = description;
+ this.tags = tags;
+ this.invariantUUID = invariantUUID;
+ this.UUID = UUID;
+ this.type = type;
+ this.category = category;
+ this.subcategory = subcategory;
+ this.resourceVendor = resourceVendor;
+ this.resourceVendorRelease = resourceVendorRelease;
+ this.serviceRole = serviceRole;
+ this.serviceEcompNaming = serviceEcompNaming;
+ this.ecompGeneratedNaming = ecompGeneratedNaming;
+ this.namingPolicy = namingPolicy;
+ this.artifactList = artifactList;
+ this.contactId = contactId;
+ this.name = name;
+ this.serviceIconPath = serviceIconPath;
+ this.icon = icon;
+ this.vendorName = vendorName;
+ this.vendorRelease = vendorRelease;
+ this.serviceVendorModelNumber = serviceVendorModelNumber;
+ this.serviceType = serviceType;
+ this.projectCode = projectCode;
+ if (category != null) {
+ String[] arr = category.split("/");
+ if (arr.length >= 2) {
+ categories = new ArrayList<>();
+ CategoryDefinition catDef = new CategoryDefinition();
+ catDef.setName(arr[0]);
+ SubCategoryDefinition subCat = new SubCategoryDefinition();
+ subCat.setName(arr[1]);
+ catDef.addSubCategory(subCat);
+ categories.add(catDef);
+ }
+ }
+ }
- if (category != null) {
- String[] arr = category.split("/");
- if (arr.length >= 2) {
- categories = new ArrayList<>();
- CategoryDefinition catDef = new CategoryDefinition();
- catDef.setName(arr[0]);
- SubCategoryDefinition subCat = new SubCategoryDefinition();
- subCat.setName(arr[1]);
- catDef.addSubCategory(subCat);
- categories.add(catDef);
- }
+ public UploadServiceInfo() {
}
- }
- public UploadServiceInfo() {
- }
- public void addSubCategory(String category, String subCategory) {
- if (category != null || subCategory != null) {
- if (categories == null) {
- categories = new ArrayList<>();
- }
- CategoryDefinition selectedCategory = null;
- for (CategoryDefinition categoryDef : categories) {
- if (categoryDef.getName().equals(category)) {
- selectedCategory = categoryDef;
- }
- }
- if (selectedCategory == null) {
- selectedCategory = new CategoryDefinition();
- selectedCategory.setName(category);
- categories.add(selectedCategory);
- }
- List<SubCategoryDefinition> subcategories = selectedCategory.getSubcategories();
- if (subcategories == null) {
- subcategories = new ArrayList<>();
- selectedCategory.setSubcategories(subcategories);
- }
- SubCategoryDefinition selectedSubcategory = null;
- for (SubCategoryDefinition subcategory : subcategories) {
- if (subcategory.getName().equals(subCategory)) {
- selectedSubcategory = subcategory;
+ public void addSubCategory(String category, String subCategory) {
+ if (category != null || subCategory != null) {
+ if (categories == null) {
+ categories = new ArrayList<>();
+ }
+ CategoryDefinition selectedCategory = null;
+ for (CategoryDefinition categoryDef : categories) {
+ if (categoryDef.getName().equals(category)) {
+ selectedCategory = categoryDef;
+ }
+ }
+ if (selectedCategory == null) {
+ selectedCategory = new CategoryDefinition();
+ selectedCategory.setName(category);
+ categories.add(selectedCategory);
+ }
+ List<SubCategoryDefinition> subcategories = selectedCategory.getSubcategories();
+ if (subcategories == null) {
+ subcategories = new ArrayList<>();
+ selectedCategory.setSubcategories(subcategories);
+ }
+ SubCategoryDefinition selectedSubcategory = null;
+ for (SubCategoryDefinition subcategory : subcategories) {
+ if (subcategory.getName().equals(subCategory)) {
+ selectedSubcategory = subcategory;
+ }
+ }
+ if (selectedSubcategory == null) {
+ selectedSubcategory = new SubCategoryDefinition();
+ selectedSubcategory.setName(subCategory);
+ subcategories.add(selectedSubcategory);
+ }
}
- }
- if (selectedSubcategory == null) {
- selectedSubcategory = new SubCategoryDefinition();
- selectedSubcategory.setName(subCategory);
- subcategories.add(selectedSubcategory);
- }
}
- }
-} \ No newline at end of file
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/User.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/User.java
index 9081e474f6..7b83dae731 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/User.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/User.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model;
import com.fasterxml.jackson.annotation.JsonInclude;
@@ -25,23 +24,17 @@ import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
import org.openecomp.sdc.be.resources.data.UserData;
+
@JsonInclude
public class User {
public static final String FORCE_DELETE_HEADER_FLAG = "FORCE_DELETE";
-
private String firstName;
-
private String lastName;
-
private String userId;
-
private String email;
-
private String role;
-
private Long lastLoginTime;
-
private UserStatusEnum status = UserStatusEnum.ACTIVE;
public User() {
@@ -52,12 +45,11 @@ public class User {
}
public User(UserData userDate) {
- this(userDate.getFirstName(), userDate.getLastName(), userDate.getUserId(), userDate.getEmail(),
- userDate.getRole(), userDate.getLastLoginTime());
+ this(userDate.getFirstName(), userDate.getLastName(), userDate.getUserId(), userDate.getEmail(), userDate.getRole(),
+ userDate.getLastLoginTime());
}
- public User(String firstName, String lastName, String userId, String emailAddress, String role,
- Long lastLoginTime) {
+ public User(String firstName, String lastName, String userId, String emailAddress, String role, Long lastLoginTime) {
this.firstName = firstName;
this.lastName = lastName;
this.userId = userId;
@@ -66,22 +58,20 @@ public class User {
this.lastLoginTime = lastLoginTime;
}
+ public User(User aUser) {
+ this(aUser.getFirstName(), aUser.getLastName(), aUser.getUserId(), aUser.getEmail(), aUser.getRole(), aUser.getLastLoginTime());
+ }
+
public void copyData(User other) {
- if(other == null) {
- return;
- }
+ if (other == null) {
+ return;
+ }
this.firstName = other.getFirstName();
this.lastName = other.getLastName();
this.userId = other.getUserId();
this.email = other.getEmail();
this.role = other.getRole();
this.lastLoginTime = other.getLastLoginTime();
-
- }
-
- public User(User aUser) {
- this(aUser.getFirstName(), aUser.getLastName(), aUser.getUserId(), aUser.getEmail(), aUser.getRole(),
- aUser.getLastLoginTime());
}
public String getFirstName() {
@@ -133,14 +123,14 @@ public class User {
this.lastLoginTime = now.getMillis();
}
- public void setLastLoginTime(Long time) {
- this.lastLoginTime = time;
- }
-
public Long getLastLoginTime() {
return this.lastLoginTime;
}
+ public void setLastLoginTime(Long time) {
+ this.lastLoginTime = time;
+ }
+
@Override
public int hashCode() {
final int prime = 31;
@@ -156,43 +146,58 @@ public class User {
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
User other = (User) obj;
if (userId == null) {
- if (other.userId != null)
+ if (other.userId != null) {
return false;
- } else if (!userId.equals(other.userId))
+ }
+ } else if (!userId.equals(other.userId)) {
return false;
+ }
if (email == null) {
- if (other.email != null)
+ if (other.email != null) {
return false;
- } else if (!email.equals(other.email))
+ }
+ } else if (!email.equals(other.email)) {
return false;
+ }
if (firstName == null) {
- if (other.firstName != null)
+ if (other.firstName != null) {
return false;
- } else if (!firstName.equals(other.firstName))
+ }
+ } else if (!firstName.equals(other.firstName)) {
return false;
+ }
if (lastName == null) {
- if (other.lastName != null)
+ if (other.lastName != null) {
return false;
- } else if (!lastName.equals(other.lastName))
+ }
+ } else if (!lastName.equals(other.lastName)) {
return false;
+ }
if (role == null) {
- if (other.role != null)
+ if (other.role != null) {
return false;
- } else if (!role.equals(other.role))
+ }
+ } else if (!role.equals(other.role)) {
return false;
+ }
if (lastLoginTime == null) {
- if (other.lastLoginTime != null)
+ if (other.lastLoginTime != null) {
return false;
- } else if (!lastLoginTime.equals(other.lastLoginTime))
+ }
+ } else if (!lastLoginTime.equals(other.lastLoginTime)) {
return false;
+ }
return true;
}
@@ -206,8 +211,7 @@ public class User {
@Override
public String toString() {
- return "User [firstName=" + firstName + ", lastName=" + lastName + ", userId=" + userId + ", email=" + email
- + ", role=" + role + ", last login time=" + lastLoginTime + "]";
+ return "User [firstName=" + firstName + ", lastName=" + lastName + ", userId=" + userId + ", email=" + email + ", role=" + role
+ + ", last login time=" + lastLoginTime + "]";
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationCache.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationCache.java
index e70ab0ec63..4c58285c12 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationCache.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationCache.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.cache;
import fj.data.Either;
-import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
-
import java.util.Map;
+import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
public interface ApplicationCache<T> {
public abstract Either<Map<String, T>, JanusGraphOperationStatus> getAll();
public abstract Either<T, JanusGraphOperationStatus> get(String uniqueId);
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java
index 25a305ed9b..d6cc01b3ef 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.cache;
import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import javax.annotation.Resource;
import lombok.Getter;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.commons.lang3.tuple.ImmutablePair;
@@ -40,52 +54,28 @@ import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
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.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.stream.Collectors;
-
@Component("application-datatype-cache")
public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefinition>, Runnable {
private static final String APPLICATION_DATA_TYPES_CACHE = "ApplicationDataTypesCache";
- private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
+ private static final Logger log = Logger.getLogger(ApplicationDataTypeCache.class.getName());
+ private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock r = rwl.readLock();
private final Lock w = rwl.writeLock();
-
- private Map<String, DataTypeDefinition> data = new HashMap<>();
-
- private ScheduledExecutorService scheduledPollingService = Executors.newScheduledThreadPool(1,
- new BasicThreadFactory.Builder().namingPattern("ApplicationDataTypeCacheThread-%d").build());
ScheduledFuture<?> scheduledFuture = null;
-
- private static final Logger log = Logger.getLogger(ApplicationDataTypeCache.class.getName());
-
+ private Map<String, DataTypeDefinition> data = new HashMap<>();
+ private ScheduledExecutorService scheduledPollingService = Executors
+ .newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("ApplicationDataTypeCacheThread-%d").build());
private int firstRunDelayInSec = 30;
private int pollingIntervalInSec = 60;
-
@Resource
private PropertyOperation propertyOperation;
-
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
@PostConstruct
public void init() {
-
- ApplicationL1CacheConfig applicationL1CacheConfig = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getApplicationL1Cache();
+ ApplicationL1CacheConfig applicationL1CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL1Cache();
if (applicationL1CacheConfig != null) {
if (applicationL1CacheConfig.getDatatypes() != null) {
ApplicationL1CacheInfo datatypesInfo = applicationL1CacheConfig.getDatatypes();
@@ -100,50 +90,47 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
}
log.trace("ApplicationDataTypesCache polling interval is {} seconds.", pollingIntervalInSec);
if (scheduledPollingService != null) {
- log.debug("Start ApplicationDataTypeCache polling task. polling interval {} seconds",
- pollingIntervalInSec);
- scheduledFuture = scheduledPollingService.scheduleAtFixedRate(this, firstRunDelayInSec,
- pollingIntervalInSec, TimeUnit.SECONDS);
+ log.debug("Start ApplicationDataTypeCache polling task. polling interval {} seconds", pollingIntervalInSec);
+ scheduledFuture = scheduledPollingService
+ .scheduleAtFixedRate(this, firstRunDelayInSec, pollingIntervalInSec, TimeUnit.SECONDS);
}
-
}
} else {
- BeEcompErrorManager.getInstance().logInternalFlowError(APPLICATION_DATA_TYPES_CACHE, "Cache is disabled",
- ErrorSeverity.INFO);
+ BeEcompErrorManager.getInstance().logInternalFlowError(APPLICATION_DATA_TYPES_CACHE, "Cache is disabled", ErrorSeverity.INFO);
}
} else {
- BeEcompErrorManager.getInstance().logInternalFlowError(APPLICATION_DATA_TYPES_CACHE, "Cache is disabled",
- ErrorSeverity.INFO);
+ BeEcompErrorManager.getInstance().logInternalFlowError(APPLICATION_DATA_TYPES_CACHE, "Cache is disabled", ErrorSeverity.INFO);
}
-
}
@PreDestroy
void destroy() {
-
if (scheduledFuture != null) {
boolean result = scheduledFuture.cancel(true);
log.debug("Stop polling task. result = {}", result);
-
scheduledFuture = null;
}
shutdownExecutor();
}
private void shutdownExecutor() {
- if (scheduledPollingService == null)
+ if (scheduledPollingService == null) {
return;
-
+ }
scheduledPollingService.shutdown(); // Disable new tasks from being
- // submitted
+
+ // submitted
try {
// Wait a while for existing tasks to terminate
if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) {
scheduledPollingService.shutdownNow(); // Cancel currently
- // executing tasks
+
+ // executing tasks
+
// Wait a while for tasks to respond to being cancelled
- if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS))
+ if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) {
log.debug("Pool did not terminate");
+ }
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
@@ -154,24 +141,17 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
}
private Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> getAllDataTypesFromGraph() {
-
- return propertyOperation
- .getAllDataTypes();
-
+ return propertyOperation.getAllDataTypes();
}
@Override
public Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> getAll() {
-
try {
-
r.lock();
if (data == null || data.isEmpty()) {
return getAllDataTypesFromGraph();
}
-
return Either.left(data);
-
} finally {
r.unlock();
}
@@ -179,19 +159,14 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
@Override
public Either<DataTypeDefinition, JanusGraphOperationStatus> get(String uniqueId) {
-
try {
r.lock();
-
if (data == null || data.isEmpty()) {
- return propertyOperation
- .getDataTypeByUid(uniqueId);
+ return propertyOperation.getDataTypeByUid(uniqueId);
} else {
- DataTypeDefinition dataTypeDefinition = data.values().stream()
- .filter(p -> p.getUniqueId().equals(uniqueId)).findFirst().orElse(null);
+ DataTypeDefinition dataTypeDefinition = data.values().stream().filter(p -> p.getUniqueId().equals(uniqueId)).findFirst().orElse(null);
if (dataTypeDefinition == null) {
- return propertyOperation
- .getDataTypeByUid(uniqueId);
+ return propertyOperation.getDataTypeByUid(uniqueId);
} else {
return Either.left(dataTypeDefinition);
}
@@ -204,9 +179,7 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
@Override
public void run() {
log.trace("run() method. polling db to fetch data types");
-
try {
-
Long start = System.currentTimeMillis();
log.trace("Start fetching all data types from db");
Either<List<DataTypeData>, JanusGraphOperationStatus> allDataTypeNodes = propertyOperation.getAllDataTypeNodes();
@@ -216,46 +189,35 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
JanusGraphOperationStatus status = allDataTypeNodes.right().value();
if (status != JanusGraphOperationStatus.OK) {
log.debug("ApplicationDataTypesCache - Failed to fetch all data types nodes");
- BeEcompErrorManager.getInstance().logInternalConnectionError("FetchDataTypes",
- "Failed to fetch data types from graph(cache)", ErrorSeverity.INFO);
+ BeEcompErrorManager.getInstance()
+ .logInternalConnectionError("FetchDataTypes", "Failed to fetch data types from graph(cache)", ErrorSeverity.INFO);
}
} else {
-
List<DataTypeData> list = allDataTypeNodes.left().value();
if (list != null) {
-
- Map<String, ImmutablePair<Long, Long>> dataTypeNameToModificationTime = list.stream()
- .collect(Collectors.toMap(p -> p.getDataTypeDataDefinition().getName(),
- p -> new ImmutablePair<>(p.getDataTypeDataDefinition().getCreationTime(),
- p.getDataTypeDataDefinition().getModificationTime())));
-
+ Map<String, ImmutablePair<Long, Long>> dataTypeNameToModificationTime = list.stream().collect(Collectors
+ .toMap(p -> p.getDataTypeDataDefinition().getName(), p -> new ImmutablePair<>(p.getDataTypeDataDefinition().getCreationTime(),
+ p.getDataTypeDataDefinition().getModificationTime())));
Map<String, ImmutablePair<Long, Long>> currentDataTypeToModificationTime = new HashMap<>();
try {
r.lock();
if (data != null) {
- currentDataTypeToModificationTime = data.values().stream().collect(Collectors.toMap(
- DataTypeDataDefinition::getName,
- p -> new ImmutablePair<>(p.getCreationTime(), p.getModificationTime())));
-
+ currentDataTypeToModificationTime = data.values().stream().collect(Collectors
+ .toMap(DataTypeDataDefinition::getName, p -> new ImmutablePair<>(p.getCreationTime(), p.getModificationTime())));
}
} finally {
r.unlock();
}
-
- boolean isChanged = compareDataTypes(dataTypeNameToModificationTime,
- currentDataTypeToModificationTime);
+ boolean isChanged = compareDataTypes(dataTypeNameToModificationTime, currentDataTypeToModificationTime);
if (isChanged) {
replaceAllData();
}
-
}
}
-
} catch (Exception e) {
log.debug("unexpected error occured", e);
-
- BeEcompErrorManager.getInstance().logInternalUnexpectedError(APPLICATION_DATA_TYPES_CACHE,
- "Failed to run refresh data types job", ErrorSeverity.INFO);
+ BeEcompErrorManager.getInstance()
+ .logInternalUnexpectedError(APPLICATION_DATA_TYPES_CACHE, "Failed to run refresh data types job", ErrorSeverity.INFO);
} finally {
try {
propertyOperation.getJanusGraphGenericDao().commit();
@@ -263,75 +225,54 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
log.trace("Failed to commit ApplicationDataTypeCache", e);
}
}
-
}
private boolean compareDataTypes(Map<String, ImmutablePair<Long, Long>> dataTypeNameToModificationTime,
- Map<String, ImmutablePair<Long, Long>> currentDataTypeToModificationTime) {
+ Map<String, ImmutablePair<Long, Long>> currentDataTypeToModificationTime) {
if (dataTypeNameToModificationTime.size() != currentDataTypeToModificationTime.size()) {
return true;
} else {
-
Set<String> currentkeySet = currentDataTypeToModificationTime.keySet();
Set<String> keySet = dataTypeNameToModificationTime.keySet();
-
if (currentkeySet.containsAll(keySet)) {
-
for (Entry<String, ImmutablePair<Long, Long>> entry : dataTypeNameToModificationTime.entrySet()) {
String dataTypeName = entry.getKey();
ImmutablePair<Long, Long> creationAndModificationTimes = entry.getValue();
- long creationTime = creationAndModificationTimes.getLeft() == null ? 0
- : creationAndModificationTimes.getLeft().longValue();
- long modificationTime = creationAndModificationTimes.getRight() == null ? 0
- : creationAndModificationTimes.getRight().longValue();
-
+ long creationTime = creationAndModificationTimes.getLeft() == null ? 0 : creationAndModificationTimes.getLeft().longValue();
+ long modificationTime = creationAndModificationTimes.getRight() == null ? 0 : creationAndModificationTimes.getRight().longValue();
ImmutablePair<Long, Long> currentEntry = currentDataTypeToModificationTime.get(dataTypeName);
long currentCreationTime = currentEntry.getLeft() == null ? 0 : currentEntry.getLeft().longValue();
- long currentModificationTime = currentEntry.getRight() == null ? 0
- : currentEntry.getRight().longValue();
-
+ long currentModificationTime = currentEntry.getRight() == null ? 0 : currentEntry.getRight().longValue();
if (creationTime > currentCreationTime || modificationTime > currentModificationTime) {
- log.debug("Datatype {} was updated. Creation Time {} vs {}. Modification Time {} vs {}",
- dataTypeName, currentCreationTime, creationTime, currentModificationTime,
- modificationTime);
+ log.debug("Datatype {} was updated. Creation Time {} vs {}. Modification Time {} vs {}", dataTypeName, currentCreationTime,
+ creationTime, currentModificationTime, modificationTime);
return true;
}
}
} else {
return true;
}
-
}
-
return false;
}
private void replaceAllData() {
-
- Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = propertyOperation
- .getAllDataTypes();
-
+ Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = propertyOperation.getAllDataTypes();
if (allDataTypes.isRight()) {
JanusGraphOperationStatus status = allDataTypes.right().value();
log.debug("Failed to fetch all data types from db. Status is {}", status);
} else {
-
try {
w.lock();
-
data = allDataTypes.left().value();
// send notification on data types change
onDataChangeEventEmit(data);
-
- BeEcompErrorManager.getInstance().logInternalFlowError("ReplaceDataTypesCache",
- "Succeed to replace the data types cache", ErrorSeverity.INFO);
-
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("ReplaceDataTypesCache", "Succeed to replace the data types cache", ErrorSeverity.INFO);
} finally {
w.unlock();
}
-
}
-
}
private void onDataChangeEventEmit(Map<String, DataTypeDefinition> newData) {
@@ -344,6 +285,7 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini
* Custom event to notify all interested in cached data changes
*/
public static class DataTypesCacheChangedEvent extends ApplicationEvent {
+
@Getter
private Map<String, DataTypeDefinition> newData;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java
index 8002939e80..5d28db9b98 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.catalog;
import static java.util.Objects.requireNonNull;
@@ -67,5 +66,4 @@ public class CatalogComponent {
public List<CategoryDefinition> getCategories() {
return categories == null ? Collections.emptyList() : ImmutableList.copyOf(categories);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/CategoryDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/CategoryDefinition.java
index 44a0362a41..635044a149 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/CategoryDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/CategoryDefinition.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.category;
import java.util.ArrayList;
@@ -50,5 +49,4 @@ public class CategoryDefinition extends CategoryDataDefinition {
}
subcategories.add(subcategory);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/GroupingDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/GroupingDefinition.java
index f8436db7db..ca0d20a40c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/GroupingDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/GroupingDefinition.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.category;
import org.openecomp.sdc.be.datatypes.category.GroupingDataDefinition;
@@ -30,5 +29,4 @@ public class GroupingDefinition extends GroupingDataDefinition {
public GroupingDefinition(GroupingDataDefinition g) {
super(g);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/SubCategoryDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/SubCategoryDefinition.java
index ed7b490b54..014b8a19e6 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/SubCategoryDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/category/SubCategoryDefinition.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.category;
import java.util.ArrayList;
@@ -49,5 +48,4 @@ public class SubCategoryDefinition extends SubCategoryDataDefinition {
}
groupings.add(groupingDefinition);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java
index c2536e70d4..f8ad169cff 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,25 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.heat;
-import org.openecomp.sdc.be.model.tosca.converters.*;
-import org.openecomp.sdc.be.model.tosca.validators.*;
+import org.openecomp.sdc.be.model.tosca.converters.HeatBooleanConverter;
+import org.openecomp.sdc.be.model.tosca.converters.HeatCommaDelimitedListConverter;
+import org.openecomp.sdc.be.model.tosca.converters.HeatJsonConverter;
+import org.openecomp.sdc.be.model.tosca.converters.HeatNumberConverter;
+import org.openecomp.sdc.be.model.tosca.converters.HeatStringConverter;
+import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
+import org.openecomp.sdc.be.model.tosca.validators.HeatBooleanValidator;
+import org.openecomp.sdc.be.model.tosca.validators.HeatCommaDelimitedListValidator;
+import org.openecomp.sdc.be.model.tosca.validators.HeatNumberValidator;
+import org.openecomp.sdc.be.model.tosca.validators.HeatStringValidator;
+import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
public enum HeatParameterType {
-
- STRING("string", HeatStringValidator.getInstance(), HeatStringConverter.getInstance()),
-
- BOOLEAN("boolean", HeatBooleanValidator.getInstance(), HeatBooleanConverter.getInstance()),
-
- NUMBER("number", HeatNumberValidator.getInstance(), HeatNumberConverter.getInstance()),
-
- JSON("json", HeatStringValidator.getInstance(), HeatJsonConverter.getInstance()),
-
- COMMA_DELIMITED_LIST("comma_delimited_list", HeatCommaDelimitedListValidator.getInstance(),
- HeatCommaDelimitedListConverter.getInstance());
-
+ STRING("string", HeatStringValidator.getInstance(), HeatStringConverter.getInstance()), BOOLEAN("boolean", HeatBooleanValidator.getInstance(),
+ HeatBooleanConverter.getInstance()), NUMBER("number", HeatNumberValidator.getInstance(), HeatNumberConverter.getInstance()), JSON("json",
+ HeatStringValidator.getInstance(), HeatJsonConverter.getInstance()), COMMA_DELIMITED_LIST("comma_delimited_list",
+ HeatCommaDelimitedListValidator.getInstance(), HeatCommaDelimitedListConverter.getInstance());
private String type;
private PropertyTypeValidator validator;
private PropertyValueConverter converter;
@@ -46,23 +46,10 @@ public enum HeatParameterType {
this.converter = converter;
}
- public String getType() {
- return type;
- }
-
- public PropertyTypeValidator getValidator() {
- return validator;
- }
-
- public PropertyValueConverter getConverter() {
- return converter;
- }
-
public static HeatParameterType isValidType(String typeName) {
if (typeName == null) {
return null;
}
-
for (HeatParameterType type : HeatParameterType.values()) {
if (type.getType().equals(typeName)) {
return type;
@@ -70,4 +57,16 @@ public enum HeatParameterType {
}
return null;
}
+
+ public String getType() {
+ return type;
+ }
+
+ public PropertyTypeValidator getValidator() {
+ return validator;
+ }
+
+ public PropertyValueConverter getConverter() {
+ return converter;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/config/ContainerInstanceTypesData.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/config/ContainerInstanceTypesData.java
index 903855b74b..341d5222a1 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/config/ContainerInstanceTypesData.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/config/ContainerInstanceTypesData.java
@@ -16,7 +16,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.config;
import java.util.Collections;
@@ -36,7 +35,6 @@ public class ContainerInstanceTypesData {
private static final Logger LOGGER = LoggerFactory.getLogger(ContainerInstanceTypesData.class);
private static final String WILDCARD = "*";
-
private final ConfigurationManager configurationManager;
public ContainerInstanceTypesData() {
@@ -50,8 +48,7 @@ public class ContainerInstanceTypesData {
* @return {@code true} if the resource instance is allowed, {@code false} otherwise
*/
public boolean isAllowedForServiceComponent(final ResourceTypeEnum resourceTypeToCheck) {
- final List<String> allowedResourceInstanceTypeList =
- getComponentAllowedList(ComponentTypeEnum.SERVICE, null);
+ final List<String> allowedResourceInstanceTypeList = getComponentAllowedList(ComponentTypeEnum.SERVICE, null);
if (CollectionUtils.isEmpty(allowedResourceInstanceTypeList)) {
return false;
}
@@ -62,13 +59,11 @@ public class ContainerInstanceTypesData {
* Checks if a resource instance type is allowed for a resource component.
*
* @param containerComponentResourceType the container component type that the instance will be added
- * @param resourceToCheck the resource instance type that will be added to the container component
+ * @param resourceToCheck the resource instance type that will be added to the container component
* @return {@code true} if the resource instance is allowed in the container component, {@code false} otherwise
*/
- public boolean isAllowedForResourceComponent(final ResourceTypeEnum containerComponentResourceType,
- final ResourceTypeEnum resourceToCheck) {
- final List<String> allowedResourceInstanceTypeList =
- getComponentAllowedList(ComponentTypeEnum.RESOURCE, containerComponentResourceType);
+ public boolean isAllowedForResourceComponent(final ResourceTypeEnum containerComponentResourceType, final ResourceTypeEnum resourceToCheck) {
+ final List<String> allowedResourceInstanceTypeList = getComponentAllowedList(ComponentTypeEnum.RESOURCE, containerComponentResourceType);
if (CollectionUtils.isEmpty(allowedResourceInstanceTypeList)) {
return false;
}
@@ -78,18 +73,15 @@ public class ContainerInstanceTypesData {
/**
* Gets the list of allowed component instances for a component type.
*
- * @param componentType the component type
+ * @param componentType the component type
* @param resourceInstanceType the instance type to check, or null for any instance
* @return the list of allowed component instances for the given component
*/
- public List<String> getComponentAllowedList(final ComponentTypeEnum componentType,
- final ResourceTypeEnum resourceInstanceType) {
- final Map<String, List<String>> componentAllowedResourceTypeMap =
- getComponentAllowedInstanceTypes().get(componentType.getValue());
+ public List<String> getComponentAllowedList(final ComponentTypeEnum componentType, final ResourceTypeEnum resourceInstanceType) {
+ final Map<String, List<String>> componentAllowedResourceTypeMap = getComponentAllowedInstanceTypes().get(componentType.getValue());
if (MapUtils.isEmpty(componentAllowedResourceTypeMap)) {
final String resourceTypeString = resourceInstanceType == null ? WILDCARD : resourceInstanceType.getValue();
- LOGGER.warn("No '{}' instance resource type configuration found for '{}'",
- componentType.getValue(), resourceTypeString);
+ LOGGER.warn("No '{}' instance resource type configuration found for '{}'", componentType.getValue(), resourceTypeString);
return Collections.emptyList();
}
return getAllowedInstanceType(resourceInstanceType, componentAllowedResourceTypeMap);
@@ -112,11 +104,9 @@ public class ContainerInstanceTypesData {
} else {
allowedInstanceResourceType = instanceAllowedResourceTypeMap.get(resourceInstanceType.getValue());
}
-
if (CollectionUtils.isEmpty(allowedInstanceResourceType)) {
return Collections.emptyList();
}
-
return allowedInstanceResourceType;
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java
index 2153e22c1d..a17e66011b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.datamodel;
import java.util.List;
@@ -30,12 +29,12 @@ import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
@Setter
public class NodeType extends ToscaElement {
- public NodeType() {
- super(ToscaElementTypeEnum.NODE_TYPE);
- }
-
private List<String> derivedFrom;
private List<String> derivedList;
private Map<String, String> derivedFromMapOfIdToName;
private Map<String, InterfaceDataDefinition> interfaceArtifacts;
+
+ public NodeType() {
+ super(ToscaElementTypeEnum.NODE_TYPE);
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplate.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplate.java
index 483e79c53b..348b849719 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplate.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/TopologyTemplate.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.datamodel;
import java.util.HashMap;
@@ -54,10 +53,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum;
@Setter
public class TopologyTemplate extends ToscaElement {
- public TopologyTemplate() {
- super(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE);
- }
-
private Map<String, PropertyDataDefinition> inputs;
private Map<String, AttributeDataDefinition> outputs;
private Map<String, MapPropertiesDataDefinition> instInputs;
@@ -83,33 +78,32 @@ public class TopologyTemplate extends ToscaElement {
private Map<String, MapInterfaceDataDefinition> componentInstInterfaces;
private Map<String, CINodeFilterDataDefinition> nodeFilterComponents;
private Map<String, SubstitutionFilterDataDefinition> substitutionFilterDataDefinitionMap;
-
- //Component Instances External References (instanceId -> ExternalRefsMap)
//-----------------------------------------------------------------------
private Map<String, MapComponentInstanceExternalRefs> mapComponentInstancesExternalRefs;
- //-----------------------------------------------------------------------
+ //Component Instances External References (instanceId -> ExternalRefsMap)
- public void addInstInterface(String compId, MapInterfaceInstanceDataDefinition
- mapInterfaceInstanceDataDefinition) {
+ public TopologyTemplate() {
+ super(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE);
+ }
+
+ //-----------------------------------------------------------------------
+ public void addInstInterface(String compId, MapInterfaceInstanceDataDefinition mapInterfaceInstanceDataDefinition) {
if (MapUtils.isEmpty(this.instInterfaces)) {
this.instInterfaces = new HashMap<>();
}
-
this.instInterfaces.put(compId, mapInterfaceInstanceDataDefinition);
}
- public void addComponentInstanceInterfaceMap(String componentInstanceId, MapInterfaceDataDefinition
- mapInterfaceDataDefinition) {
+ public void addComponentInstanceInterfaceMap(String componentInstanceId, MapInterfaceDataDefinition mapInterfaceDataDefinition) {
if (MapUtils.isEmpty(this.componentInstInterfaces)) {
this.componentInstInterfaces = new HashMap<>();
}
-
this.componentInstInterfaces.put(componentInstanceId, mapInterfaceDataDefinition);
}
/**
- * Adds component instance to composition of topology template Note that component instance will be overrided in
- * case if the topology template already contains a component instance with the same name
+ * Adds component instance to composition of topology template Note that component instance will be overrided in case if the topology template
+ * already contains a component instance with the same name
*
* @param componentInstance
*/
@@ -120,8 +114,7 @@ public class TopologyTemplate extends ToscaElement {
if (MapUtils.isEmpty(getCompositions())) {
compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), new CompositionDataDefinition());
}
- if (MapUtils
- .isEmpty(getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances())) {
+ if (MapUtils.isEmpty(getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances())) {
getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).setComponentInstances(new HashMap<>());
}
getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances()
@@ -141,10 +134,9 @@ public class TopologyTemplate extends ToscaElement {
return instances;
}
-
/**
- * Sets map of component instances to composition of topology template Note that component instances will be
- * overrided in case if the topology template already contains a component instances
+ * Sets map of component instances to composition of topology template Note that component instances will be overrided in case if the topology
+ * template already contains a component instances
*
* @param instances
*/
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java
index 78d4763245..c176ec812b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.jsonjanusgraph.datamodel;
import java.util.HashMap;
@@ -65,15 +64,14 @@ public abstract class ToscaElement {
private String creatorFullName;
private String lastUpdaterUserId;
private String lastUpdaterFullName;
-
private Map<String, String> allVersions;
private String toscaVersion;
- protected ToscaElement(ToscaElementTypeEnum toscaType){
+ protected ToscaElement(ToscaElementTypeEnum toscaType) {
this.toscaType = toscaType;
}
-
// metadata properties
+
// ----------------------------
public Object getMetadataValue(JsonPresentationFields name) {
return getMetadataValueOrDefault(name, null);
@@ -89,13 +87,14 @@ public abstract class ToscaElement {
public void setMetadataValue(JsonPresentationFields name, Object value) {
setMetadataValue(name.getPresentation(), value);
}
-
+
public void setMetadataValue(String name, Object value) {
if (metadata == null) {
metadata = new HashMap<>();
}
metadata.put(name, value);
}
+
// --------------------
public String getUUID() {
return (String) getMetadataValue(JsonPresentationFields.UUID);
@@ -124,17 +123,19 @@ public abstract class ToscaElement {
public String getSystemName() {
return (String) getMetadataValue(JsonPresentationFields.SYSTEM_NAME);
}
+
public void setSystemName(String systemName) {
setMetadataValue(JsonPresentationFields.SYSTEM_NAME, systemName);
}
- public void setLifecycleState(LifecycleStateEnum state) {
- if(state != null)
- setMetadataValue(JsonPresentationFields.LIFECYCLE_STATE, state.name());
+ public LifecycleStateEnum getLifecycleState() {
+ return LifecycleStateEnum.findState((String) getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
}
- public LifecycleStateEnum getLifecycleState() {
- return LifecycleStateEnum.findState( (String) getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
+ public void setLifecycleState(LifecycleStateEnum state) {
+ if (state != null) {
+ setMetadataValue(JsonPresentationFields.LIFECYCLE_STATE, state.name());
+ }
}
public Long getCreationDate() {
@@ -145,36 +146,39 @@ public abstract class ToscaElement {
setMetadataValue(JsonPresentationFields.CREATION_DATE, currentDate);
}
- public void setLastUpdateDate(Long currentDate) {
- setMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE, currentDate);
- }
public Long getLastUpdateDate() {
return (Long) getMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE);
}
+ public void setLastUpdateDate(Long currentDate) {
+ setMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE, currentDate);
+ }
+
public String getUniqueId() {
return (String) getMetadataValue(JsonPresentationFields.UNIQUE_ID);
}
+
public void setUniqueId(String uniqueId) {
- setMetadataValue(JsonPresentationFields.UNIQUE_ID, uniqueId);
+ setMetadataValue(JsonPresentationFields.UNIQUE_ID, uniqueId);
}
public void setHighestVersion(Boolean isHighest) {
- setMetadataValue(JsonPresentationFields.HIGHEST_VERSION, isHighest);
-
+ setMetadataValue(JsonPresentationFields.HIGHEST_VERSION, isHighest);
}
+
public Boolean isHighestVersion() {
return (Boolean) getMetadataValue(JsonPresentationFields.HIGHEST_VERSION);
-
}
+
public ResourceTypeEnum getResourceType() {
String resourceType = (String) getMetadataValue(JsonPresentationFields.RESOURCE_TYPE);
return resourceType != null ? ResourceTypeEnum.valueOf(resourceType) : null;
}
public void setResourceType(ResourceTypeEnum resourceType) {
- if(resourceType != null)
+ if (resourceType != null) {
setMetadataValue(JsonPresentationFields.RESOURCE_TYPE, resourceType.name());
+ }
}
public ComponentTypeEnum getComponentType() {
@@ -182,36 +186,41 @@ public abstract class ToscaElement {
}
public void setComponentType(ComponentTypeEnum componentType) {
- if(componentType != null)
+ if (componentType != null) {
setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, componentType.name());
+ }
}
- public String getDerivedFromGenericType(){
+ public String getDerivedFromGenericType() {
return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE);
}
- public void setDerivedFromGenericType(String derivedFromGenericType){
+ public void setDerivedFromGenericType(String derivedFromGenericType) {
setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE, derivedFromGenericType);
}
- public String getDerivedFromGenericVersion(){
+ public String getDerivedFromGenericVersion() {
return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION);
}
- public void setDerivedFromGenericVersion(String derivedFromGenericVersion){
+ public void setDerivedFromGenericVersion(String derivedFromGenericVersion) {
setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION, derivedFromGenericVersion);
}
- public Boolean isArchived() { return (Boolean) getMetadataValue(JsonPresentationFields.IS_ARCHIVED); }
+ public Boolean isArchived() {
+ return (Boolean) getMetadataValue(JsonPresentationFields.IS_ARCHIVED);
+ }
- public void setArchived(Boolean archived) { setMetadataValue(JsonPresentationFields.IS_ARCHIVED, archived); }
+ public void setArchived(Boolean archived) {
+ setMetadataValue(JsonPresentationFields.IS_ARCHIVED, archived);
+ }
public Long getArchiveTime() {
Object archiveTime = getMetadataValue(JsonPresentationFields.ARCHIVE_TIME);
- if (archiveTime instanceof Integer){
- return Long.valueOf((Integer)getMetadataValue(JsonPresentationFields.ARCHIVE_TIME));
+ if (archiveTime instanceof Integer) {
+ return Long.valueOf((Integer) getMetadataValue(JsonPresentationFields.ARCHIVE_TIME));
}
- return (Long)archiveTime;
+ return (Long) archiveTime;
}
public void setArchiveTime(Long archiveTime) {
@@ -229,11 +238,11 @@ public abstract class ToscaElement {
public void generateUUID() {
String prevUUID = getUUID();
String version = getVersion();
- if ((prevUUID == null && NodeTypeOperation.uuidNormativeNewVersion.matcher(version).matches()) || NodeTypeOperation.uuidNewVersion.matcher(version).matches()) {
+ if ((prevUUID == null && NodeTypeOperation.uuidNormativeNewVersion.matcher(version).matches()) || NodeTypeOperation.uuidNewVersion
+ .matcher(version).matches()) {
UUID uuid = UUID.randomUUID();
setUUID(uuid.toString());
MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, uuid.toString());
}
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnum.java
index 1e3620ba14..e470192889 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnum.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElementTypeEnum.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,30 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.datamodel;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
public enum ToscaElementTypeEnum {
- NODE_TYPE("node_type"),
- TOPOLOGY_TEMPLATE("topology_template");
-
+ NODE_TYPE("node_type"), TOPOLOGY_TEMPLATE("topology_template");
String value;
- private ToscaElementTypeEnum(String value){
+
+ private ToscaElementTypeEnum(String value) {
this.value = value;
}
- public static VertexTypeEnum getVertexTypeByToscaType(ToscaElementTypeEnum toscaType ){
- switch ( toscaType ){
- case NODE_TYPE :
- return VertexTypeEnum.NODE_TYPE;
- case TOPOLOGY_TEMPLATE :
- return VertexTypeEnum.TOPOLOGY_TEMPLATE;
- default :
- return null;
+ public static VertexTypeEnum getVertexTypeByToscaType(ToscaElementTypeEnum toscaType) {
+ switch (toscaType) {
+ case NODE_TYPE:
+ return VertexTypeEnum.NODE_TYPE;
+ case TOPOLOGY_TEMPLATE:
+ return VertexTypeEnum.TOPOLOGY_TEMPLATE;
+ default:
+ return null;
}
}
public String getValue() {
return value;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnum.java
index 308f2db445..41819b4d80 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnum.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/enums/JsonConstantKeysEnum.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.enums;
public enum JsonConstantKeysEnum {
-
+ // @formatter:off
COMPOSITION("composition"),
CAPABILITIES("capabilities"),
REQUIREMENTS("requirements"),
@@ -29,6 +28,7 @@ public enum JsonConstantKeysEnum {
INPUTS("inputs"),
GROUPS("groups"),
INSTANCE_PROPERIES("instanceProperties");
+ // @formatter:on
private String value;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java
index 782867a856..c580062732 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
+import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation.Action.ARCHIVE;
+import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation.Action.RESTORE;
+
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+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.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
@@ -40,12 +48,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.*;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation.Action.ARCHIVE;
-import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation.Action.RESTORE;
-
/**
* Created by yavivi on 25/03/2018.
*/
@@ -53,22 +55,17 @@ import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperat
public class ArchiveOperation extends BaseOperation {
private static final Logger log = Logger.getLogger(ArchiveOperation.class.getName());
-
@Autowired
private IGraphLockOperation graphLockOperation;
- public enum Action {
- ARCHIVE, RESTORE;
- }
-
- public ArchiveOperation(JanusGraphDao janusGraphDao, IGraphLockOperation graphLockOperation){
+ public ArchiveOperation(JanusGraphDao janusGraphDao, IGraphLockOperation graphLockOperation) {
this.janusGraphDao = janusGraphDao;
this.graphLockOperation = graphLockOperation;
}
public Either<List<String>, ActionStatus> archiveComponent(String componentId) {
final Either<GraphVertex, JanusGraphOperationStatus> vertexResult = this.janusGraphDao.getVertexById(componentId);
- if (vertexResult.isLeft()){
+ if (vertexResult.isLeft()) {
return doAction(ARCHIVE, vertexResult.left().value());
} else {
return Either.right(onError(ARCHIVE.name(), componentId, vertexResult.right().value()));
@@ -77,38 +74,37 @@ public class ArchiveOperation extends BaseOperation {
public Either<List<String>, ActionStatus> restoreComponent(String componentId) {
final Either<GraphVertex, JanusGraphOperationStatus> vertexResult = this.janusGraphDao.getVertexById(componentId);
- if (vertexResult.isLeft()){
+ if (vertexResult.isLeft()) {
return doAction(RESTORE, vertexResult.left().value());
} else {
return Either.right(onError(RESTORE.name(), componentId, vertexResult.right().value()));
}
}
- public ActionStatus onVspRestored(String csarId){
+ public ActionStatus onVspRestored(String csarId) {
return onVspStateChanged(RESTORE, csarId);
}
- public ActionStatus onVspArchived(String csarId){
+ public ActionStatus onVspArchived(String csarId) {
return onVspStateChanged(ARCHIVE, csarId);
}
private ActionStatus onVspStateChanged(Action action, String csarId) {
Map<GraphPropertyEnum, Object> props = new HashMap<>();
props.put(GraphPropertyEnum.CSAR_UUID, csarId);
- Either<List<GraphVertex>, JanusGraphOperationStatus> vfsE = janusGraphDao
- .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props);
- return vfsE.either(vList -> setVspArchived(action, vList), s -> onError("VSP_"+action.name(), csarId, s));
+ Either<List<GraphVertex>, JanusGraphOperationStatus> vfsE = janusGraphDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props);
+ return vfsE.either(vList -> setVspArchived(action, vList), s -> onError("VSP_" + action.name(), csarId, s));
}
private ActionStatus setVspArchived(Action action, List<GraphVertex> vList) {
if (!vList.isEmpty()) {
//Find & Lock the highest version component
GraphVertex highestVersion = this.getHighestVersionFrom(vList.get(0));
- StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType());
- if (lockStatus != StorageOperationStatus.OK){
+ StorageOperationStatus lockStatus = this.graphLockOperation
+ .lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
return onError(action.name(), highestVersion.getUniqueId(), JanusGraphOperationStatus.ALREADY_LOCKED);
}
-
try {
//Set isVspArchived flag
for (GraphVertex v : vList) {
@@ -117,84 +113,67 @@ public class ArchiveOperation extends BaseOperation {
v.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, val);
janusGraphDao.updateVertex(v);
}
- return commitAndCheck("VSP_"+action.name(), vList.toString());
+ return commitAndCheck("VSP_" + action.name(), vList.toString());
} finally {
this.graphLockOperation.unlockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType());
}
-
}
return ActionStatus.OK;
}
public List<String> setArchivedOriginsFlagInComponentInstances(GraphVertex compositionService) {
List<String> ciUidsWithArchivedOrigins = new LinkedList();
- Either<List<GraphVertex>, JanusGraphOperationStatus> instanceOfVerticesE = janusGraphDao.getChildrenVertices(compositionService, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.NoParse);
- Either<List<GraphVertex>, JanusGraphOperationStatus> proxyOfVerticesE = janusGraphDao.getChildrenVertices(compositionService, EdgeLabelEnum.PROXY_OF, JsonParseFlagEnum.NoParse);
-
+ Either<List<GraphVertex>, JanusGraphOperationStatus> instanceOfVerticesE = janusGraphDao
+ .getChildrenVertices(compositionService, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.NoParse);
+ Either<List<GraphVertex>, JanusGraphOperationStatus> proxyOfVerticesE = janusGraphDao
+ .getChildrenVertices(compositionService, EdgeLabelEnum.PROXY_OF, JsonParseFlagEnum.NoParse);
List<GraphVertex> all = new LinkedList<>();
- if (instanceOfVerticesE.isLeft()){
+ if (instanceOfVerticesE.isLeft()) {
all.addAll(instanceOfVerticesE.left().value());
}
- if (proxyOfVerticesE.isLeft()){
+ if (proxyOfVerticesE.isLeft()) {
all.addAll(proxyOfVerticesE.left().value());
}
-
- List<GraphVertex> archivedOrigins = all.stream().filter(v -> Boolean.TRUE.equals(v.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED))).collect(Collectors.toList());
+ List<GraphVertex> archivedOrigins = all.stream().filter(v -> Boolean.TRUE.equals(v.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED)))
+ .collect(Collectors.toList());
List<String> archivedOriginsUids = archivedOrigins.stream().map(GraphVertex::getUniqueId).collect(Collectors.toList());
-
Map<String, CompositionDataDefinition> compositionsJson = (Map<String, CompositionDataDefinition>) compositionService.getJson();
-
if (compositionsJson != null) {
CompositionDataDefinition composition = compositionsJson.get(JsonConstantKeysEnum.COMPOSITION.getValue());
if (composition != null) {
-
//Get all component instances from composition
Map<String, ComponentInstanceDataDefinition> componentInstances = composition.getComponentInstances();
-
//Extract component instances uids that has archived origins
- ciUidsWithArchivedOrigins = componentInstances.
- values().
- stream().
- //filter CIs whose origins are marked as archived (componentUid is in archivedOriginsUids) the second condition handles the PROXY_OF case)
- filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids.contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID))).
- map(ComponentInstanceDataDefinition::getUniqueId).collect(Collectors.toList());
-
+ ciUidsWithArchivedOrigins = componentInstances.values().stream().
+ //filter CIs whose origins are marked as archived (componentUid is in archivedOriginsUids) the second condition handles the PROXY_OF case)
+ filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids
+ .contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID)))
+ .map(ComponentInstanceDataDefinition::getUniqueId).collect(Collectors.toList());
//set archived origins flag
- componentInstances.
- values().
- stream().
- filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids.contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID))).
- forEach( ci -> ci.setOriginArchived(true));
-
+ componentInstances.values().stream().filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids
+ .contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID))).forEach(ci -> ci.setOriginArchived(true));
}
}
-
return ciUidsWithArchivedOrigins;
}
- private Either<List<String>, ActionStatus> doAction(Action action, GraphVertex componentVertex){
-
+ private Either<List<String>, ActionStatus> doAction(Action action, GraphVertex componentVertex) {
GraphVertex highestVersion = this.getHighestVersionFrom(componentVertex);
-
if (action.equals(ARCHIVE) && isInCheckoutState(highestVersion)) {
return Either.right(ActionStatus.INVALID_SERVICE_STATE);
}
-
//Lock the Highest Version
- StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType());
- if (lockStatus != StorageOperationStatus.OK){
+ StorageOperationStatus lockStatus = this.graphLockOperation
+ .lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
return Either.right(onError(action.name(), componentVertex.getUniqueId(), JanusGraphOperationStatus.ALREADY_LOCKED));
}
-
//Refetch latest version with full parsing
- highestVersion = this.janusGraphDao
- .getVertexById(highestVersion.getUniqueId(), JsonParseFlagEnum.ParseAll).left().value();
-
+ highestVersion = this.janusGraphDao.getVertexById(highestVersion.getUniqueId(), JsonParseFlagEnum.ParseAll).left().value();
try {
//Get Catalog and Archive Roots
GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().value();
GraphVertex archiveRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.ARCHIVE_ROOT).left().value();
-
if (action == ARCHIVE) {
archiveEdges(catalogRoot, archiveRoot, highestVersion);
} else if (action == RESTORE) {
@@ -202,10 +181,9 @@ public class ArchiveOperation extends BaseOperation {
}
setPropertiesByAction(highestVersion, action);
janusGraphDao.updateVertex(highestVersion);
-
List<String> affectedComponentIds = handleParents(highestVersion, catalogRoot, archiveRoot, action);
ActionStatus sc = commitAndCheck(action.name(), highestVersion.getUniqueId());
- return sc == ActionStatus.OK ? Either.left(affectedComponentIds) : Either.right(sc);
+ return sc == ActionStatus.OK ? Either.left(affectedComponentIds) : Either.right(sc);
} finally {
this.graphLockOperation.unlockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType());
}
@@ -213,14 +191,14 @@ public class ArchiveOperation extends BaseOperation {
private ActionStatus commitAndCheck(String action, String componentId) {
JanusGraphOperationStatus status = janusGraphDao.commit();
- if (!status.equals(JanusGraphOperationStatus.OK)){
+ if (!status.equals(JanusGraphOperationStatus.OK)) {
return onError(action, componentId, status);
}
return ActionStatus.OK;
}
private boolean isInCheckoutState(GraphVertex v) {
- if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name().equals(v.getMetadataProperty(GraphPropertyEnum.STATE))){
+ if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name().equals(v.getMetadataProperty(GraphPropertyEnum.STATE))) {
return true;
}
return false;
@@ -228,6 +206,7 @@ public class ArchiveOperation extends BaseOperation {
/**
* Walks on children until highest version is reached
+ *
* @param v
* @return
*/
@@ -235,16 +214,14 @@ public class ArchiveOperation extends BaseOperation {
Either<GraphVertex, JanusGraphOperationStatus> childVertexE = janusGraphDao
.getChildVertex(v, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
GraphVertex highestVersionVertex = v;
-
while (childVertexE.isLeft()) {
highestVersionVertex = childVertexE.left().value();
- childVertexE = janusGraphDao
- .getChildVertex(highestVersionVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ childVertexE = janusGraphDao.getChildVertex(highestVersionVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
}
return highestVersionVertex;
}
- private boolean isHighestVersion(GraphVertex v){
+ private boolean isHighestVersion(GraphVertex v) {
Boolean highest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION);
return highest != null && highest;
}
@@ -254,12 +231,11 @@ public class ArchiveOperation extends BaseOperation {
.getParentVertex(v, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll);
List<String> affectedCompIds = new ArrayList();
affectedCompIds.add(v.getUniqueId());
-
- while (parentVertexE.isLeft()){
+ while (parentVertexE.isLeft()) {
GraphVertex cv = parentVertexE.left().value();
affectedCompIds.add(cv.getUniqueId());
boolean isHighestVersion = isHighestVersion(cv);
- if (isHighestVersion){
+ if (isHighestVersion) {
if (action == ARCHIVE) {
archiveEdges(catalogRoot, archiveRoot, cv);
} else {
@@ -268,8 +244,7 @@ public class ArchiveOperation extends BaseOperation {
}
setPropertiesByAction(cv, action);
janusGraphDao.updateVertex(cv);
- parentVertexE = janusGraphDao
- .getParentVertex(cv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll);
+ parentVertexE = janusGraphDao.getParentVertex(cv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll);
}
return affectedCompIds;
}
@@ -288,7 +263,6 @@ public class ArchiveOperation extends BaseOperation {
private void setPropertiesByAction(GraphVertex v, Action action) {
long now = System.currentTimeMillis();
-
boolean isArchived = action == ARCHIVE ? true : false;
v.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, isArchived);
v.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, now);
@@ -298,7 +272,7 @@ public class ArchiveOperation extends BaseOperation {
private ActionStatus onError(String action, String componentId, JanusGraphOperationStatus s) {
ActionStatus ret = ActionStatus.GENERAL_ERROR;
- if (s == JanusGraphOperationStatus.NOT_FOUND){
+ if (s == JanusGraphOperationStatus.NOT_FOUND) {
ret = ActionStatus.RESOURCE_NOT_FOUND;
} else if (s == JanusGraphOperationStatus.ALREADY_LOCKED) {
ret = ActionStatus.COMPONENT_IN_USE;
@@ -307,4 +281,6 @@ public class ArchiveOperation extends BaseOperation {
log.error("error occurred when trying to {} {}. Return code is: {}", action, componentId, retCodeVal);
return ret;
}
+
+ public enum Action {ARCHIVE, RESTORE;}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java
index baf1d22cb2..fd2f5d5bbf 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java
@@ -17,10 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Collectors;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.apache.commons.lang3.tuple.ImmutableTriple;
@@ -57,54 +66,49 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.slf4j.MDC;
-import java.util.*;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
@org.springframework.stereotype.Component("artifacts-operations")
public class ArtifactsOperations extends BaseOperation {
- private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}";
- private static final Logger log = Logger.getLogger(ArtifactsOperations.class.getName());
- public Either<ArtifactDefinition, StorageOperationStatus> addArtifactToComponent(ArtifactDefinition artifactInfo,
- Component component, NodeTypeEnum type, boolean failIfExist, String instanceId) {
+ private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}";
+ private static final Logger log = Logger.getLogger(ArtifactsOperations.class.getName());
+ public Either<ArtifactDefinition, StorageOperationStatus> addArtifactToComponent(ArtifactDefinition artifactInfo, Component component,
+ NodeTypeEnum type, boolean failIfExist, String instanceId) {
String parentId = component.getUniqueId();
String artifactId = artifactInfo.getUniqueId();
if (artifactId == null && artifactInfo.getEsId() != null) {
artifactId = artifactInfo.getEsId();
}
- Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(component, artifactInfo, type, artifactId, instanceId, false, false);
+ Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(component, artifactInfo, type, artifactId, instanceId,
+ false, false);
if (status.isRight()) {
-
- log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), parentId, status.right().value());
- BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value()));
+ log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), parentId,
+ status.right().value());
+ BeEcompErrorManager.getInstance()
+ .logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value()));
return Either.right(status.right().value());
} else {
-
ArtifactDataDefinition artifactData = status.left().value();
-
ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData);
log.debug("The returned ArtifactDefintion is {}", artifactDefResult);
return Either.left(artifactDefResult);
}
-
}
- public Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResource(ArtifactDefinition artifactInfo,
- Component component, String artifactId, NodeTypeEnum type, String instanceId, boolean isUpdate) {
-
+ public Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResource(ArtifactDefinition artifactInfo, Component component,
+ String artifactId, NodeTypeEnum type, String instanceId,
+ boolean isUpdate) {
String id = component.getUniqueId();
- Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(component, artifactInfo, type, artifactId, instanceId, isUpdate, false);
+ Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(component, artifactInfo, type, artifactId, instanceId,
+ isUpdate, false);
if (status.isRight()) {
-
- log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), id, status.right().value());
- BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value()));
+ log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), id,
+ status.right().value());
+ BeEcompErrorManager.getInstance()
+ .logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value()));
return Either.right(status.right().value());
} else {
-
ArtifactDataDefinition artifactData = status.left().value();
-
ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData);
log.debug("The returned ArtifactDefinition is {}", artifactDefResult);
return Either.left(artifactDefResult);
@@ -113,7 +117,6 @@ public class ArtifactsOperations extends BaseOperation {
public Either<Boolean, StorageOperationStatus> isCloneNeeded(String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum type) {
ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
-
Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type);
EdgeLabelEnum edgeLabelEnum = triple.getLeft();
return super.isCloneNeeded(parentId, edgeLabelEnum);
@@ -123,7 +126,8 @@ public class ArtifactsOperations extends BaseOperation {
return getArtifactById(parentId, id, null, null);
}
- public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String parentId, String id, ComponentTypeEnum componentType, String containerId) {
+ public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String parentId, String id, ComponentTypeEnum componentType,
+ String containerId) {
Either<ArtifactDefinition, StorageOperationStatus> result = null;
ArtifactDataDefinition foundArtifact = null;
if (componentType != null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
@@ -138,90 +142,79 @@ public class ArtifactsOperations extends BaseOperation {
if (foundArtifact == null) {
foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.TOSCA_ARTIFACTS);
}
-
if (foundArtifact == null) {
foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.ARTIFACTS);
}
-
if (foundArtifact == null) {
foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
}
- if (foundArtifact == null) {
- foundArtifact = findInterfaceArtifact(parentId, id);
-
- }
-
+ if (foundArtifact == null) {
+ foundArtifact = findInterfaceArtifact(parentId, id);
+ }
if (foundArtifact == null) {
result = Either.right(StorageOperationStatus.NOT_FOUND);
return result;
}
-
ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(null, foundArtifact);
return Either.left(artifactDefResult);
+ }
+
+ private ArtifactDataDefinition findInterfaceArtifact(String parentId, String id) {
+ Either<Map<String, InterfaceDefinition>, JanusGraphOperationStatus> dataFromGraph = getDataFromGraph(parentId, EdgeLabelEnum.INTERFACE);
+ if (dataFromGraph.isRight()) {
+ log.debug("failed to fetch interfaces {} for tosca element with id {}, error {}", id, parentId, dataFromGraph.right().value());
+ return null;
+ }
+ Map<String, InterfaceDefinition> interfaceDefinitionMap = dataFromGraph.left().value();
+ if (interfaceDefinitionMap == null) {
+ return null;
+ }
+ Collection<InterfaceDefinition> interfaces = interfaceDefinitionMap.values();
+ if (interfaces == null) {
+ return null;
+ }
+ for (InterfaceDataDefinition interfaceDataDefinition : interfaces) {
+ Map<String, OperationDataDefinition> operationsMap = interfaceDataDefinition.getOperations();
+ if (operationsMap == null) {
+ return null;
+ }
+ ArtifactDataDefinition implementationArtifact = getArtifactDataDefinition(id, operationsMap);
+ if (implementationArtifact != null) {
+ return implementationArtifact;
+ }
+ }
+ return null;
+ }
+ private ArtifactDataDefinition getArtifactDataDefinition(String id, Map<String, OperationDataDefinition> operationsMap) {
+ for (OperationDataDefinition operationDataDefinition : operationsMap.values()) {
+ ArtifactDataDefinition implementationArtifact = operationDataDefinition.getImplementation();
+ if (implementationArtifact != null) {
+ String uniqueId = implementationArtifact.getUniqueId();
+ if (id.equals(uniqueId)) {
+ return implementationArtifact;
+ }
+ }
+ }
+ return null;
}
- private ArtifactDataDefinition findInterfaceArtifact(String parentId, String id) {
- Either<Map<String, InterfaceDefinition>, JanusGraphOperationStatus> dataFromGraph = getDataFromGraph(parentId, EdgeLabelEnum.INTERFACE);
- if (dataFromGraph.isRight()){
- log.debug("failed to fetch interfaces {} for tosca element with id {}, error {}", id, parentId ,dataFromGraph.right().value());
- return null;
- }
-
- Map<String, InterfaceDefinition> interfaceDefinitionMap = dataFromGraph.left().value();
- if(interfaceDefinitionMap == null) {
- return null;
- }
- Collection<InterfaceDefinition> interfaces = interfaceDefinitionMap.values();
- if (interfaces == null){
- return null;
- }
- for (InterfaceDataDefinition interfaceDataDefinition : interfaces){
- Map<String, OperationDataDefinition> operationsMap = interfaceDataDefinition.getOperations();
- if (operationsMap == null) {
- return null;
- }
- ArtifactDataDefinition implementationArtifact = getArtifactDataDefinition(id, operationsMap);
- if (implementationArtifact != null)
- return implementationArtifact;
- }
- return null;
- }
-
- private ArtifactDataDefinition getArtifactDataDefinition(String id,
- Map<String, OperationDataDefinition> operationsMap) {
- for(OperationDataDefinition operationDataDefinition : operationsMap.values()){
- ArtifactDataDefinition implementationArtifact = operationDataDefinition.getImplementation();
- if(implementationArtifact != null){
- String uniqueId = implementationArtifact.getUniqueId();
- if (id.equals(uniqueId)) {
- return implementationArtifact;
- }
- }
- }
- return null;
- }
-
-
- public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
- Either<ArtifactDefinition, StorageOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact);
+ public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type,
+ boolean deleteMandatoryArtifact) {
+ Either<ArtifactDefinition, StorageOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact);
if (status.isRight()) {
-
log.debug("Failed to delete artifact {} of resource {}", artifactId, id);
-
BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value()));
return Either.right(status.right().value());
} else {
-
return Either.left(status.left().value());
}
}
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
-
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType,
+ ArtifactGroupTypeEnum groupType, String instanceId) {
Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, parentType);
EdgeLabelEnum edgeLabelEnum = triple.getLeft();
-
Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> foundArtifact = null;
Map<String, ArtifactDefinition> resMap = new HashMap<>();
foundArtifact = getArtifactByLabel(parentId, instanceId, edgeLabelEnum);
@@ -229,9 +222,7 @@ public class ArtifactsOperations extends BaseOperation {
log.debug("Failed to find artifact in component {} with label {} ", parentId, edgeLabelEnum);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(foundArtifact.right().value()));
}
-
resMap.putAll(foundArtifact.left().value());
-
return Either.left(resMap);
}
@@ -242,11 +233,13 @@ public class ArtifactsOperations extends BaseOperation {
*/
public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getAllInstanceArtifacts(String parentId, String instanceId) {
Map<String, ArtifactDataDefinition> resMap = new HashMap<>();
- Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> instArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> instArtifacts = getInstanceArtifactsByLabel(parentId, instanceId,
+ EdgeLabelEnum.INSTANCE_ARTIFACTS);
if (instArtifacts.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(instArtifacts.right().value()));
}
- Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> deployInstArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> deployInstArtifacts = getInstanceArtifactsByLabel(parentId, instanceId,
+ EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
if (deployInstArtifacts.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deployInstArtifacts.right().value()));
}
@@ -256,29 +249,25 @@ public class ArtifactsOperations extends BaseOperation {
}
public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId) {
-
Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> foundArtifact = null;
Map<String, ArtifactDefinition> resMap = new HashMap<>();
foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.ARTIFACTS);
if (foundArtifact.isLeft()) {
resMap.putAll(foundArtifact.left().value());
-
}
foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
if (foundArtifact.isLeft()) {
resMap.putAll(foundArtifact.left().value());
-
}
foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.TOSCA_ARTIFACTS);
if (foundArtifact.isLeft()) {
resMap.putAll(foundArtifact.left().value());
}
return Either.left(resMap);
-
}
- public Either<ArtifactDefinition, StorageOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
-
+ public Either<ArtifactDefinition, StorageOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type,
+ boolean deleteMandatoryArtifact) {
Either<ArtifactDefinition, StorageOperationStatus> artifactData = this.getArtifactById(id, artifactId);
if (artifactData.isRight()) {
log.debug("Failed to find artifact in component {} with id {} ", id, artifactId);
@@ -290,30 +279,29 @@ public class ArtifactsOperations extends BaseOperation {
// return Either.left(artifactData.left().value());
isMandatory = true;
}
-
- Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactDefinition.getArtifactGroupType(), type);
+ Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactDefinition.getArtifactGroupType(),
+ type);
EdgeLabelEnum edgeLabelEnum = triple.getLeft();
VertexTypeEnum vertexTypeEnum = triple.getRight();
-
if (!isMandatory) {
- StorageOperationStatus status = deleteToscaDataElement(id, edgeLabelEnum, vertexTypeEnum, artifactDefinition.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL);
- if (status != StorageOperationStatus.OK)
+ StorageOperationStatus status = deleteToscaDataElement(id, edgeLabelEnum, vertexTypeEnum, artifactDefinition.getArtifactLabel(),
+ JsonPresentationFields.ARTIFACT_LABEL);
+ if (status != StorageOperationStatus.OK) {
return Either.right(status);
+ }
}
-
return Either.left(artifactData.left().value());
-
}
- private void updateUUID(Map<String, ArtifactDefinition> deploymentArtifacts, ArtifactDefinition updateArtifactData, String oldChecksum, String oldVesrion, boolean isUpdate, EdgeLabelEnum edgeLabel, String prevArtUid) {
+ private void updateUUID(Map<String, ArtifactDefinition> deploymentArtifacts, ArtifactDefinition updateArtifactData, String oldChecksum,
+ String oldVesrion, boolean isUpdate, EdgeLabelEnum edgeLabel, String prevArtUid) {
if (oldVesrion == null || oldVesrion.isEmpty()) {
oldVesrion = "0";
}
String currentChecksum = updateArtifactData.getArtifactChecksum();
-
if (isUpdate) {
final ArtifactTypeEnum type = ArtifactTypeEnum.parse(updateArtifactData.getArtifactType());
- if(type == null) {
+ if (type == null) {
generateUUIDForNonHeatArtifactType(updateArtifactData, oldChecksum, oldVesrion, currentChecksum);
return;
}
@@ -327,34 +315,30 @@ public class ArtifactsOperations extends BaseOperation {
case HEAT_NET:
case HEAT_VOL:
boolean changed = false;
- Optional<Entry<String, ArtifactDefinition>> any = deploymentArtifacts.entrySet()
- .stream()
- .filter(e -> e.getKey().equals(updateArtifactData.getArtifactLabel()))
- .findAny();
- if ( any.isPresent() ){
- if ( !any.get().getValue().getArtifactChecksum().equals(updateArtifactData.getArtifactChecksum()) ){
+ Optional<Entry<String, ArtifactDefinition>> any = deploymentArtifacts.entrySet().stream()
+ .filter(e -> e.getKey().equals(updateArtifactData.getArtifactLabel())).findAny();
+ if (any.isPresent()) {
+ if (!any.get().getValue().getArtifactChecksum().equals(updateArtifactData.getArtifactChecksum())) {
changed = true;
}
}
- Optional<Entry<String, ArtifactDefinition>> anyEnv = deploymentArtifacts.entrySet()
- .stream()
- .filter(e -> prevArtUid.equals(e.getValue().getGeneratedFromId()))
- .findAny();
- if ( anyEnv.isPresent() && anyEnv.get().getValue().getHeatParamUpdated()){
+ Optional<Entry<String, ArtifactDefinition>> anyEnv = deploymentArtifacts.entrySet().stream()
+ .filter(e -> prevArtUid.equals(e.getValue().getGeneratedFromId())).findAny();
+ if (anyEnv.isPresent() && anyEnv.get().getValue().getHeatParamUpdated()) {
String newCheckSum = sortAndCalculateChecksumForHeatParameters(updateArtifactData.getHeatParameters());
- if ( !anyEnv.get().getValue().getArtifactChecksum().equals(newCheckSum) ){
+ if (!anyEnv.get().getValue().getArtifactChecksum().equals(newCheckSum)) {
changed = true;
anyEnv.get().getValue().setArtifactChecksum(newCheckSum);
UUID uuid = UUID.randomUUID();
anyEnv.get().getValue().setArtifactUUID(uuid.toString());
}
}
- if ( changed && anyEnv.isPresent() ){
- generateUUID(updateArtifactData, oldVesrion);
- anyEnv.get().getValue().setGeneratedFromId(updateArtifactData.getUniqueId());
- anyEnv.get().getValue().setDuplicated(false);
- anyEnv.get().getValue().setArtifactVersion(updateArtifactData.getArtifactVersion());
- anyEnv.get().getValue().setHeatParamUpdated(false);
+ if (changed && anyEnv.isPresent()) {
+ generateUUID(updateArtifactData, oldVesrion);
+ anyEnv.get().getValue().setGeneratedFromId(updateArtifactData.getUniqueId());
+ anyEnv.get().getValue().setDuplicated(false);
+ anyEnv.get().getValue().setArtifactVersion(updateArtifactData.getArtifactVersion());
+ anyEnv.get().getValue().setHeatParamUpdated(false);
}
break;
default:
@@ -366,7 +350,8 @@ public class ArtifactsOperations extends BaseOperation {
}
}
- private void generateUUIDForNonHeatArtifactType(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion, String currentChecksum) {
+ private void generateUUIDForNonHeatArtifactType(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion,
+ String currentChecksum) {
if (oldChecksum == null || oldChecksum.isEmpty()) {
if (currentChecksum != null) {
generateUUID(artifactData, oldVesrion);
@@ -376,72 +361,68 @@ public class ArtifactsOperations extends BaseOperation {
}
}
- public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv,
- ArtifactDefinition artifactHeat, Component component, NodeTypeEnum parentType, boolean failIfExist, String instanceId) {
+ public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat,
+ Component component, NodeTypeEnum parentType, boolean failIfExist,
+ String instanceId) {
artifactHeatEnv.setGeneratedFromId(artifactHeat.getUniqueId());
return addArtifactToComponent(artifactHeatEnv, component, parentType, failIfExist, instanceId);
}
- public Either<ArtifactDefinition, StorageOperationStatus> getHeatArtifactByHeatEnvId(final String parentId,
- final ArtifactDefinition heatEnv,
+ public Either<ArtifactDefinition, StorageOperationStatus> getHeatArtifactByHeatEnvId(final String parentId, final ArtifactDefinition heatEnv,
final String containerId,
final ComponentTypeEnum componentType) {
return getArtifactById(parentId, heatEnv.getGeneratedFromId(), componentType, containerId);
}
- public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact(Component component, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) {
-
- Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> artifactsEither = getArtifactByLabel(component.getUniqueId(), instanceId, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
+ public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact(Component component, ArtifactDefinition artifactEnvInfo,
+ String artifactId, String newArtifactId, NodeTypeEnum type,
+ String instanceId) {
+ Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> artifactsEither = getArtifactByLabel(component.getUniqueId(), instanceId,
+ EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
return updateHeatEnvArtifact(artifactsEither, component, artifactEnvInfo, artifactId, newArtifactId, type, instanceId);
}
private Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact(
- Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> artifactsEither, Component component,
- ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) {
-
+ Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> artifactsEither, Component component, ArtifactDefinition artifactEnvInfo,
+ String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) {
String id = component.getUniqueId();
if (artifactsEither.isRight()) {
log.debug("Failed to find artifacts in component {} with id {} ", id, artifactsEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(artifactsEither.right().value()));
}
-
Map<String, ArtifactDefinition> artifacts = artifactsEither.left().value();
List<ArtifactDefinition> envList = artifacts.values().stream()
- .filter(a -> a.getGeneratedFromId() != null && a.getGeneratedFromId().equals(artifactId))
- .collect(Collectors.toList());
+ .filter(a -> a.getGeneratedFromId() != null && a.getGeneratedFromId().equals(artifactId)).collect(Collectors.toList());
if (envList != null && !envList.isEmpty()) {
envList.forEach(a -> {
a.setGeneratedFromId(newArtifactId);
updateArtifactOnResource(a, component, a.getUniqueId(), type, instanceId, true);
-
});
-
}
return Either.left(artifactEnvInfo);
}
- public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifactOnInstance(
- Component component, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) {
-
+ public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifactOnInstance(Component component, ArtifactDefinition artifactEnvInfo,
+ String artifactId, String newArtifactId,
+ NodeTypeEnum type, String instanceId) {
String id = component.getUniqueId();
- Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> artifactsEither = getArtifactByLabel(id, instanceId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> artifactsEither = getArtifactByLabel(id, instanceId,
+ EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
return updateHeatEnvArtifact(artifactsEither, component, artifactEnvInfo, artifactId, newArtifactId, type, instanceId);
}
- public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, Component parent, NodeTypeEnum type) {
- return updateArtifactOnResource(artifactInfo, parent, artifactInfo.getUniqueId(), type, null, true);
+ public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, Component parent,
+ NodeTypeEnum type) {
+ return updateArtifactOnResource(artifactInfo, parent, artifactInfo.getUniqueId(), type, null, true);
}
-
///////////////////////////////////////////// private methods ////////////////////////////////////////////////////
-
protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactDefinition artifactInfo, ArtifactDataDefinition artifactDefResult) {
log.debug("The object returned after create property is {}", artifactDefResult);
-
ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult);
- if (artifactInfo != null)
+ if (artifactInfo != null) {
propertyDefResult.setPayload(artifactInfo.getPayloadData());
-
+ }
List<HeatParameterDefinition> parameters = new ArrayList<>();
/*
* StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters); if ((heatParametersOfNode.equals(StorageOperationStatus.OK))
@@ -457,15 +438,15 @@ public class ArtifactsOperations extends BaseOperation {
log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, containerId, artifactsEither.right().value());
return null;
}
-
Map<String, MapArtifactDataDefinition> artifacts = artifactsEither.left().value();
-
MapArtifactDataDefinition artifactsPerInstance = artifacts.get(parentId);
if (artifactsPerInstance == null) {
- log.debug("failed to fetch artifacts for instance {} in tosca element with id {}, error {}", parentId, containerId, artifactsEither.right().value());
+ log.debug("failed to fetch artifacts for instance {} in tosca element with id {}, error {}", parentId, containerId,
+ artifactsEither.right().value());
return null;
}
- Optional<ArtifactDataDefinition> op = artifactsPerInstance.getMapToscaDataDefinition().values().stream().filter(p -> p.getUniqueId().equals(id)).findAny();
+ Optional<ArtifactDataDefinition> op = artifactsPerInstance.getMapToscaDataDefinition().values().stream()
+ .filter(p -> p.getUniqueId().equals(id)).findAny();
if (op.isPresent()) {
foundArtifact = op.get();
}
@@ -479,7 +460,6 @@ public class ArtifactsOperations extends BaseOperation {
log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, artifactsEither.right().value());
return null;
}
-
Map<String, ArtifactDataDefinition> artifacts = artifactsEither.left().value();
Optional<ArtifactDataDefinition> op = artifacts.values().stream().filter(p -> p.getUniqueId().equals(id)).findAny();
if (op.isPresent()) {
@@ -488,8 +468,10 @@ public class ArtifactsOperations extends BaseOperation {
return foundArtifact;
}
- private Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> getArtifactByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
- Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> artifactsEither = getArtifactsDataByLabel(parentId, instanceId, edgeLabelEnum);
+ private Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> getArtifactByLabel(String parentId, String instanceId,
+ EdgeLabelEnum edgeLabelEnum) {
+ Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> artifactsEither = getArtifactsDataByLabel(parentId, instanceId,
+ edgeLabelEnum);
if (artifactsEither.isRight()) {
log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, artifactsEither.right().value());
return Either.right(artifactsEither.right().value());
@@ -498,19 +480,23 @@ public class ArtifactsOperations extends BaseOperation {
return Either.left(convertArtifactMapToArtifactDefinitionMap(artifactDataMap));
}
- private Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> getArtifactsDataByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
- return edgeLabelEnum.isInstanceArtifactsLabel() ? getInstanceArtifactsByLabel(parentId, instanceId, edgeLabelEnum) : getDataFromGraph(parentId, edgeLabelEnum);
+ private Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> getArtifactsDataByLabel(String parentId, String instanceId,
+ EdgeLabelEnum edgeLabelEnum) {
+ return edgeLabelEnum.isInstanceArtifactsLabel() ? getInstanceArtifactsByLabel(parentId, instanceId, edgeLabelEnum)
+ : getDataFromGraph(parentId, edgeLabelEnum);
}
private Map<String, ArtifactDefinition> convertArtifactMapToArtifactDefinitionMap(Map<String, ArtifactDataDefinition> artifactDataMap) {
Map<String, ArtifactDefinition> artMap = new HashMap<>();
if (artifactDataMap != null && !artifactDataMap.isEmpty()) {
- artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue())));
+ artMap = artifactDataMap.entrySet().stream()
+ .collect(Collectors.toMap(Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue())));
}
return artMap;
}
- private Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
+ private Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId,
+ EdgeLabelEnum edgeLabelEnum) {
Either<Map<String, MapArtifactDataDefinition>, JanusGraphOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
if (resultEither.isRight()) {
log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, resultEither.right().value());
@@ -521,7 +507,8 @@ public class ArtifactsOperations extends BaseOperation {
return artifactPerInstance != null ? Either.left(artifactPerInstance.getMapToscaDataDefinition()) : Either.left(new HashMap<>());
}
- private Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> getEdgeLabelEnumFromArtifactGroupType(ArtifactGroupTypeEnum groupType, NodeTypeEnum nodeType) {
+ private Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> getEdgeLabelEnumFromArtifactGroupType(ArtifactGroupTypeEnum groupType,
+ NodeTypeEnum nodeType) {
EdgeLabelEnum edgeLabelEnum;
VertexTypeEnum vertexTypeEnum;
Boolean isDeepElement = false;
@@ -560,27 +547,24 @@ public class ArtifactsOperations extends BaseOperation {
}
// }
return new ImmutableTriple<>(edgeLabelEnum, isDeepElement, vertexTypeEnum);
-
}
- public Either<ArtifactDataDefinition, StorageOperationStatus> updateArtifactOnGraph(Component component, ArtifactDefinition artifactInfo, NodeTypeEnum type, String artifactId, String instanceId, boolean isUpdate, boolean isDeletePlaceholder) {
+ public Either<ArtifactDataDefinition, StorageOperationStatus> updateArtifactOnGraph(Component component, ArtifactDefinition artifactInfo,
+ NodeTypeEnum type, String artifactId, String instanceId,
+ boolean isUpdate, boolean isDeletePlaceholder) {
String componentId = component.getUniqueId();
Either<ArtifactDataDefinition, StorageOperationStatus> res = null;
ArtifactDefinition artifactToUpdate = new ArtifactDefinition(artifactInfo);
ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
-
Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type);
EdgeLabelEnum edgeLabelEnum = triple.getLeft();
VertexTypeEnum vertexTypeEnum = triple.getRight();
-
Either<Boolean, StorageOperationStatus> isNeedToCloneEither = isCloneNeeded(componentId, edgeLabelEnum);
if (isNeedToCloneEither.isRight()) {
log.debug("Failed check is clone needed {}", componentId);
return Either.right(isNeedToCloneEither.right().value());
-
}
boolean isNeedToClone = isNeedToCloneEither.left().value();
-
String prevArtUid = artifactToUpdate.getUniqueId();
if (artifactId == null || isNeedToClone) {
String uniqueId;
@@ -591,17 +575,17 @@ public class ArtifactsOperations extends BaseOperation {
}
prevArtUid = artifactToUpdate.getUniqueId();
artifactToUpdate.setUniqueId(uniqueId);
- if (!isDeletePlaceholder)
+ if (!isDeletePlaceholder) {
artifactToUpdate.setEsId(uniqueId);
- } else
+ }
+ } else {
artifactToUpdate.setUniqueId(artifactId);
-
+ }
Map<String, ArtifactDefinition> artifacts = new HashMap<>();
Map<String, MapArtifactDataDefinition> artifactInst = null;
if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
-
- Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum);
-
+ Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> artifactsEither = this
+ .getDataFromGraph(componentId, edgeLabelEnum);
if (artifactsEither.isLeft() && artifactsEither.left().value() != null && !artifactsEither.left().value().isEmpty()) {
artifacts = convertArtifactMapToArtifactDefinitionMap(artifactsEither.left().value());
if (isNeedToClone && artifacts != null) {
@@ -609,8 +593,8 @@ public class ArtifactsOperations extends BaseOperation {
}
}
} else {
-
- Either<Map<String, MapArtifactDataDefinition>, JanusGraphOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum);
+ Either<Map<String, MapArtifactDataDefinition>, JanusGraphOperationStatus> artifactsEither = this
+ .getDataFromGraph(componentId, edgeLabelEnum);
if (artifactsEither.isLeft()) {
artifactInst = artifactsEither.left().value();
if (isNeedToClone && artifactInst != null) {
@@ -630,27 +614,25 @@ public class ArtifactsOperations extends BaseOperation {
oldVersion = oldArtifactData.getArtifactVersion();
//duplicated flag didn't receive from UI, take from DB
artifactToUpdate.setDuplicated(oldArtifactData.getDuplicated());
-
- if (isNeedToClone)
+ if (isNeedToClone) {
artifactToUpdate.setDuplicated(Boolean.FALSE);
- else {
+ } else {
if (artifactToUpdate.getDuplicated()) {
String uniqueId = "";
- if(type != NodeTypeEnum.ResourceInstance)
+ if (type != NodeTypeEnum.ResourceInstance) {
uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel());
- else
+ } else {
uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel());
-
+ }
artifactToUpdate.setUniqueId(uniqueId);
- if (!isDeletePlaceholder)
+ if (!isDeletePlaceholder) {
artifactToUpdate.setEsId(uniqueId);
+ }
artifactToUpdate.setDuplicated(Boolean.FALSE);
}
}
}
-
updateUUID(artifacts, artifactToUpdate, oldChecksum, oldVersion, isUpdate, edgeLabelEnum, prevArtUid);
-
if (artifactInfo.getPayloadData() == null) {
if (!artifactToUpdate.getMandatory() || artifactToUpdate.getEsId() != null) {
artifactToUpdate.setEsId(artifactToUpdate.getUniqueId());
@@ -660,17 +642,17 @@ public class ArtifactsOperations extends BaseOperation {
artifactToUpdate.setEsId(artifactToUpdate.getUniqueId());
}
}
-
StorageOperationStatus status = StorageOperationStatus.OK;
if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
List<ArtifactDefinition> toscaDataList = new ArrayList<>();
toscaDataList.add(artifactToUpdate);
-
if (isNeedToClone && artifacts != null) {
- artifacts.values().stream().filter(a -> !a.getArtifactLabel().equals(artifactToUpdate.getArtifactLabel())).forEach(toscaDataList::add);
- }else{
- if ( artifacts != null ) {
- artifacts.values().stream().filter(a -> artifactToUpdate.getUniqueId().equals(a.getGeneratedFromId())).forEach(toscaDataList::add);
+ artifacts.values().stream().filter(a -> !a.getArtifactLabel().equals(artifactToUpdate.getArtifactLabel()))
+ .forEach(toscaDataList::add);
+ } else {
+ if (artifacts != null) {
+ artifacts.values().stream().filter(a -> artifactToUpdate.getUniqueId().equals(a.getGeneratedFromId()))
+ .forEach(toscaDataList::add);
}
}
status = updateToscaDataOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, JsonPresentationFields.ARTIFACT_LABEL);
@@ -683,42 +665,39 @@ public class ArtifactsOperations extends BaseOperation {
if (artifactInst != null) {
MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId);
if (artifatcsOnInstance != null) {
- Map<String, ArtifactDataDefinition> mapToscaDataDefinition = artifatcsOnInstance
- .getMapToscaDataDefinition();
- ArtifactDataDefinition artifactDataDefinitionToUpdate = new ArtifactDataDefinition(
- artifactToUpdate);
+ Map<String, ArtifactDataDefinition> mapToscaDataDefinition = artifatcsOnInstance.getMapToscaDataDefinition();
+ ArtifactDataDefinition artifactDataDefinitionToUpdate = new ArtifactDataDefinition(artifactToUpdate);
mapToscaDataDefinition.put(artifactToUpdate.getArtifactLabel(), artifactDataDefinitionToUpdate);
}
-
for (Entry<String, MapArtifactDataDefinition> e : artifactInst.entrySet()) {
- List<ArtifactDataDefinition> toscaDataListPerInst = e.getValue().getMapToscaDataDefinition()
- .values().stream().collect(Collectors.toList());
+ List<ArtifactDataDefinition> toscaDataListPerInst = e.getValue().getMapToscaDataDefinition().values().stream()
+ .collect(Collectors.toList());
List<String> pathKeysPerInst = new ArrayList<>();
pathKeysPerInst.add(e.getKey());
- status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum,
- toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.ARTIFACT_LABEL);
+ status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataListPerInst,
+ pathKeysPerInst, JsonPresentationFields.ARTIFACT_LABEL);
if (status != StorageOperationStatus.OK) {
- log.debug(
- "Failed to update atifacts group for instance {} in component {} edge type {} error {}",
- instanceId, componentId, edgeLabelEnum, status);
+ log.debug("Failed to update atifacts group for instance {} in component {} edge type {} error {}", instanceId,
+ componentId, edgeLabelEnum, status);
res = Either.right(status);
break;
}
}
}
} else {
- status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, pathKeys, JsonPresentationFields.ARTIFACT_LABEL);
+ status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, pathKeys,
+ JsonPresentationFields.ARTIFACT_LABEL);
}
}
- if (status == StorageOperationStatus.OK)
+ if (status == StorageOperationStatus.OK) {
res = Either.left(artifactToUpdate);
- else
+ } else {
res = Either.right(status);
+ }
return res;
}
public void generateUUID(ArtifactDataDefinition artifactData, String oldVesrion) {
-
UUID uuid = UUID.randomUUID();
artifactData.setArtifactUUID(uuid.toString());
MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, uuid.toString());
@@ -735,44 +714,46 @@ public class ArtifactsOperations extends BaseOperation {
artifactData.setArtifactVersion(String.valueOf(newVersion));
}
- public Either<ArtifactDataDefinition, StorageOperationStatus> removeArtifactOnGraph(ArtifactDefinition artifactFromGraph, String componentId, String instanceId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
-
+ public Either<ArtifactDataDefinition, StorageOperationStatus> removeArtifactOnGraph(ArtifactDefinition artifactFromGraph, String componentId,
+ String instanceId, NodeTypeEnum type,
+ boolean deleteMandatoryArtifact) {
Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactFromGraph.getArtifactGroupType(), type);
EdgeLabelEnum edgeLabelEnum = triple.getLeft();
VertexTypeEnum vertexTypeEnum = triple.getRight();
-
if (deleteMandatoryArtifact || !(artifactFromGraph.getMandatory() || artifactFromGraph.getServiceApi())) {
StorageOperationStatus status;
if (triple.getMiddle()) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(instanceId);
- status = deleteToscaDataDeepElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), pathKeys, JsonPresentationFields.ARTIFACT_LABEL);
+ status = deleteToscaDataDeepElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), pathKeys,
+ JsonPresentationFields.ARTIFACT_LABEL);
} else {
- status = deleteToscaDataElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL);
+ status = deleteToscaDataElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(),
+ JsonPresentationFields.ARTIFACT_LABEL);
}
- if (status != StorageOperationStatus.OK)
+ if (status != StorageOperationStatus.OK) {
return Either.right(status);
+ }
}
return Either.left(artifactFromGraph);
-
}
- public Either<ArtifactDataDefinition, StorageOperationStatus> deleteArtifactWithCloningOnGraph(String componentId, ArtifactDefinition artifactToDelete, NodeTypeEnum type, String instanceId, boolean deleteMandatoryArtifact) {
-
+ public Either<ArtifactDataDefinition, StorageOperationStatus> deleteArtifactWithCloningOnGraph(String componentId,
+ ArtifactDefinition artifactToDelete,
+ NodeTypeEnum type, String instanceId,
+ boolean deleteMandatoryArtifact) {
Either<ArtifactDataDefinition, StorageOperationStatus> result = null;
Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactToDelete.getArtifactGroupType(), type);
EdgeLabelEnum edgeLabel = triple.getLeft();
VertexTypeEnum vertexLabel = triple.getRight();
-
Boolean deleteElement = deleteMandatoryArtifact || !(artifactToDelete.getMandatory() || artifactToDelete.getServiceApi());
Map<String, ToscaDataDefinition> artifacts = null;
GraphVertex parentVertex = null;
Either<Map<String, ToscaDataDefinition>, JanusGraphOperationStatus> getArtifactsRes = null;
-
- Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", componentId, getToscaElementRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ",
+ componentId, getToscaElementRes.right().value());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getToscaElementRes.right().value()));
}
if (result == null) {
@@ -785,7 +766,8 @@ public class ArtifactsOperations extends BaseOperation {
if (result == null) {
artifacts = getArtifactsRes.left().value();
if (triple.getMiddle()) {
- artifacts.values().forEach(ma -> ((MapArtifactDataDefinition) ma).getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE)));
+ artifacts.values()
+ .forEach(ma -> ((MapArtifactDataDefinition) ma).getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE)));
MapArtifactDataDefinition artifatcsOnInstance = (MapArtifactDataDefinition) artifacts.get(instanceId);
if (artifatcsOnInstance != null && deleteElement) {
artifatcsOnInstance.getMapToscaDataDefinition().remove(artifactToDelete.getArtifactLabel());
@@ -799,8 +781,7 @@ public class ArtifactsOperations extends BaseOperation {
artifactToDelete.setDuplicated(Boolean.TRUE);
}
if (artifacts != null) {
- JanusGraphOperationStatus
- status = janusGraphDao.deleteEdgeByDirection(parentVertex, Direction.OUT, edgeLabel);
+ JanusGraphOperationStatus status = janusGraphDao.deleteEdgeByDirection(parentVertex, Direction.OUT, edgeLabel);
if (status != JanusGraphOperationStatus.OK) {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
} else if (MapUtils.isNotEmpty(artifacts)) {
@@ -818,11 +799,8 @@ public class ArtifactsOperations extends BaseOperation {
public String sortAndCalculateChecksumForHeatParameters(List<HeatParameterDataDefinition> heatParameters) {
StrBuilder sb = new StrBuilder();
- heatParameters.stream()
- .sorted(Comparator.comparingInt(HeatParameterDataDefinition::hashCode))
- .map(HeatParameterDataDefinition::hashCode)
- .collect(Collectors.toSet())
- .forEach(sb::append);
+ heatParameters.stream().sorted(Comparator.comparingInt(HeatParameterDataDefinition::hashCode)).map(HeatParameterDataDefinition::hashCode)
+ .collect(Collectors.toSet()).forEach(sb::append);
return GeneralUtility.calculateMD5Base64EncodedByString(sb.toString());
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java
index 1f2ef528cf..ba49b00fa4 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.jsonjanusgraph.operations;
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.UUID;
+import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
@@ -62,36 +69,29 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.*;
-import java.util.stream.Collectors;
-
/**
* public abstract class BaseOperation provides base operation functionality and common fields
- *
*/
public abstract class BaseOperation {
- private static final String FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS = "Failed remove tosca data vertex of the tosca element {} by label {}. Status is {}. ";
- private static final String FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS = "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ";
- private static final String FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS = "Failed to get tosca element {} upon adding the properties. Status is {}. ";
- private static final Logger log = Logger.getLogger(BaseOperation.class.getName());
public static final String VF_MODULE = "org.openecomp.groups.VfModule";
-
+ private static final String FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS = "Failed remove tosca data vertex of the tosca element {} by label {}. Status is {}. ";
+ private static final String FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS = "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ";
+ private static final String FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS = "Failed to get tosca element {} upon adding the properties. Status is {}. ";
+ private static final Logger log = Logger.getLogger(BaseOperation.class.getName());
@Autowired
protected JanusGraphDao janusGraphDao;
-
@Autowired
protected NodeTypeOperation nodeTypeOperation;
-
@Autowired
protected TopologyTemplateOperation topologyTemplateOperation;
-
-// @Autowired
+ // @Autowired
protected HealingPipelineDao healingPipelineDao;
public void setJanusGraphDao(JanusGraphDao janusGraphDao) {
this.janusGraphDao = janusGraphDao;
}
+
/**
* Returns reference to appropriate toscaTemplateOperation
*
@@ -101,13 +101,13 @@ public abstract class BaseOperation {
public ToscaElementOperation getToscaElementOperation(ComponentTypeEnum componentType) {
ToscaElementOperation operation;
switch (componentType) {
- case SERVICE:
- case RESOURCE:
- operation = topologyTemplateOperation;
- break;
- default:
- operation = nodeTypeOperation;
- break;
+ case SERVICE:
+ case RESOURCE:
+ operation = topologyTemplateOperation;
+ break;
+ default:
+ operation = nodeTypeOperation;
+ break;
}
return operation;
}
@@ -121,15 +121,15 @@ public abstract class BaseOperation {
public ToscaElementOperation getToscaElementOperation(ToscaElementTypeEnum toscaElementType) {
ToscaElementOperation operation;
switch (toscaElementType) {
- case TOPOLOGY_TEMPLATE:
- operation = topologyTemplateOperation;
- break;
- case NODE_TYPE:
- operation = nodeTypeOperation;
- break;
- default:
- operation = null;
- break;
+ case TOPOLOGY_TEMPLATE:
+ operation = topologyTemplateOperation;
+ break;
+ case NODE_TYPE:
+ operation = nodeTypeOperation;
+ break;
+ default:
+ operation = null;
+ break;
}
return operation;
}
@@ -143,18 +143,19 @@ public abstract class BaseOperation {
public ToscaElementOperation getToscaElementOperation(VertexTypeEnum toscaElementType) {
ToscaElementOperation operation;
switch (toscaElementType) {
- case TOPOLOGY_TEMPLATE:
- operation = topologyTemplateOperation;
- break;
- case NODE_TYPE:
- operation = nodeTypeOperation;
- break;
- default:
- operation = null;
- break;
+ case TOPOLOGY_TEMPLATE:
+ operation = topologyTemplateOperation;
+ break;
+ case NODE_TYPE:
+ operation = nodeTypeOperation;
+ break;
+ default:
+ operation = null;
+ break;
}
return operation;
}
+
/**
* Converts received vertex to User object
*
@@ -165,33 +166,30 @@ public abstract class BaseOperation {
User owner = new User();
owner.setUserId((String) ownerV.property(GraphPropertyEnum.USERID.getProperty()).value());
VertexProperty<Object> property = ownerV.property(GraphPropertyEnum.ROLE.getProperty());
- if(property != null && property.isPresent() ){
+ if (property != null && property.isPresent()) {
owner.setRole((String) property.value());
}
-
property = ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty());
- if(property != null && property.isPresent() ){
+ if (property != null && property.isPresent()) {
owner.setFirstName((String) ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty()).value());
}
-
property = ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty());
- if( property != null && property.isPresent() ){
+ if (property != null && property.isPresent()) {
owner.setLastName((String) ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty()).value());
}
-
property = ownerV.property(GraphPropertyEnum.EMAIL.getProperty());
- if( property != null && property.isPresent() ){
+ if (property != null && property.isPresent()) {
owner.setEmail((String) ownerV.property(GraphPropertyEnum.EMAIL.getProperty()).value());
}
-
property = ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty());
- if( property != null && property.isPresent() ){
+ if (property != null && property.isPresent()) {
owner.setLastLoginTime((Long) ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty()).value());
}
return owner;
}
- protected <T extends ToscaDataDefinition> Either<Map<String, T>, JanusGraphOperationStatus> getDataFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) {
+ protected <T extends ToscaDataDefinition> Either<Map<String, T>, JanusGraphOperationStatus> getDataFromGraph(GraphVertex componentV,
+ EdgeLabelEnum edgelabel) {
Either<Pair<GraphVertex, Map<String, T>>, JanusGraphOperationStatus> dataVertex = getDataAndVertexFromGraph(componentV, edgelabel);
if (dataVertex.isRight()) {
return Either.right(dataVertex.right().value());
@@ -201,7 +199,8 @@ public abstract class BaseOperation {
}
@SuppressWarnings("unchecked")
- protected <T extends ToscaDataDefinition> Either<Pair<GraphVertex, Map<String, T>>, JanusGraphOperationStatus> getDataAndVertexFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) {
+ protected <T extends ToscaDataDefinition> Either<Pair<GraphVertex, Map<String, T>>, JanusGraphOperationStatus> getDataAndVertexFromGraph(
+ GraphVertex componentV, EdgeLabelEnum edgelabel) {
Either<GraphVertex, JanusGraphOperationStatus> dataVertex = getDataVertex(componentV, edgelabel);
if (dataVertex.isRight()) {
return Either.right(dataVertex.right().value());
@@ -212,12 +211,13 @@ public abstract class BaseOperation {
return Either.left(pair);
}
- protected <T extends ToscaDataDefinition> Either<GraphVertex, JanusGraphOperationStatus> getDataVertex(GraphVertex componentV, EdgeLabelEnum edgelabel) {
- Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
- .getChildVertex(componentV, edgelabel, JsonParseFlagEnum.ParseJson);
+ protected <T extends ToscaDataDefinition> Either<GraphVertex, JanusGraphOperationStatus> getDataVertex(GraphVertex componentV,
+ EdgeLabelEnum edgelabel) {
+ Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao.getChildVertex(componentV, edgelabel, JsonParseFlagEnum.ParseJson);
if (childVertex.isRight()) {
if (childVertex.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
- log.debug("failed to fetch {} for tosca element with id {}, error {}", edgelabel, componentV.getUniqueId(), childVertex.right().value());
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", edgelabel, componentV.getUniqueId(),
+ childVertex.right().value());
}
return Either.right(childVertex.right().value());
}
@@ -232,15 +232,15 @@ public abstract class BaseOperation {
* @param edgelabel
* @return
*/
- public <T extends ToscaDataDefinition> Either<Map<String, T>, JanusGraphOperationStatus> getDataFromGraph(String toscaElementUid, EdgeLabelEnum edgelabel) {
-
+ public <T extends ToscaDataDefinition> Either<Map<String, T>, JanusGraphOperationStatus> getDataFromGraph(String toscaElementUid,
+ EdgeLabelEnum edgelabel) {
Either<Map<String, T>, JanusGraphOperationStatus> result = null;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", toscaElementUid, status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ",
+ toscaElementUid, status);
result = Either.right(status);
}
if (result == null) {
@@ -250,12 +250,10 @@ public abstract class BaseOperation {
}
public Either<GraphVertex, JanusGraphOperationStatus> findUserVertex(String userId) {
- return janusGraphDao
- .getVertexByPropertyAndLabel(GraphPropertyEnum.USERID, userId, VertexTypeEnum.USER, JsonParseFlagEnum.NoParse);
+ return janusGraphDao.getVertexByPropertyAndLabel(GraphPropertyEnum.USERID, userId, VertexTypeEnum.USER, JsonParseFlagEnum.NoParse);
}
/**
- *
* @param elemementId
* @param label
* @return
@@ -271,7 +269,8 @@ public abstract class BaseOperation {
.getChildVertex(toscaElementVertex, label, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
if (childVertex.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
- log.debug("failed to fetch {} for tosca element with id {}, error {}", label, toscaElementVertex.getUniqueId(), childVertex.right().value());
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", label, toscaElementVertex.getUniqueId(),
+ childVertex.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value()));
}
return Either.left(Boolean.FALSE);
@@ -290,7 +289,8 @@ public abstract class BaseOperation {
}
}
- protected Either<GraphVertex, JanusGraphOperationStatus> updateOrCopyOnUpdate(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label) {
+ protected Either<GraphVertex, JanusGraphOperationStatus> updateOrCopyOnUpdate(GraphVertex dataVertex, GraphVertex toscaElementVertex,
+ EdgeLabelEnum label) {
Iterator<Edge> edges = dataVertex.getVertex().edges(Direction.IN, label.name());
int edgeCount = 0;
Edge edgeToRemove = null;
@@ -298,8 +298,7 @@ public abstract class BaseOperation {
Edge edge = edges.next();
++edgeCount;
Vertex outVertex = edge.outVertex();
- String outId = (String) janusGraphDao
- .getProperty((JanusGraphVertex) outVertex, GraphPropertyEnum.UNIQUE_ID.getProperty());
+ String outId = (String) janusGraphDao.getProperty((JanusGraphVertex) outVertex, GraphPropertyEnum.UNIQUE_ID.getProperty());
if (toscaElementVertex.getUniqueId().equals(outId)) {
edgeToRemove = edge;
}
@@ -309,45 +308,47 @@ public abstract class BaseOperation {
return Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
}
switch (edgeCount) {
- case 0:
- // error
- log.debug("No edges {} to vertex {}", label, dataVertex.getUniqueId());
- return Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
- case 1:
- // update
- log.trace("Only one edge {} to vertex {}. Update vertex", label, dataVertex.getUniqueId());
- return janusGraphDao.updateVertex(dataVertex);
- default:
- // copy on update
- log.trace("More than one edge {} to vertex {}. Need to clone vertex", label, dataVertex.getUniqueId());
- return cloneDataVertex(dataVertex, toscaElementVertex, label, edgeToRemove);
- }
- }
-
- private Either<GraphVertex, JanusGraphOperationStatus> cloneDataVertex(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label, Edge edgeToRemove) {
+ case 0:
+ // error
+ log.debug("No edges {} to vertex {}", label, dataVertex.getUniqueId());
+ return Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
+ case 1:
+ // update
+ log.trace("Only one edge {} to vertex {}. Update vertex", label, dataVertex.getUniqueId());
+ return janusGraphDao.updateVertex(dataVertex);
+ default:
+ // copy on update
+ log.trace("More than one edge {} to vertex {}. Need to clone vertex", label, dataVertex.getUniqueId());
+ return cloneDataVertex(dataVertex, toscaElementVertex, label, edgeToRemove);
+ }
+ }
+
+ private Either<GraphVertex, JanusGraphOperationStatus> cloneDataVertex(GraphVertex dataVertex, GraphVertex toscaElementVertex,
+ EdgeLabelEnum label, Edge edgeToRemove) {
GraphVertex newDataVertex = new GraphVertex(dataVertex.getLabel());
String id = IdBuilderUtils.generateChildId(toscaElementVertex.getUniqueId(), dataVertex.getLabel());
newDataVertex.cloneData(dataVertex);
newDataVertex.setUniqueId(id);
-
Either<GraphVertex, JanusGraphOperationStatus> createVertex = janusGraphDao.createVertex(newDataVertex);
if (createVertex.isRight()) {
log.debug("Failed to clone data vertex for {} error {}", dataVertex.getUniqueId(), createVertex.right().value());
return createVertex;
}
newDataVertex = createVertex.left().value();
- JanusGraphOperationStatus
- createEdge = janusGraphDao
+ JanusGraphOperationStatus createEdge = janusGraphDao
.createEdge(toscaElementVertex, newDataVertex, label, janusGraphDao.getEdgeProperties(edgeToRemove));
if (createEdge != JanusGraphOperationStatus.OK) {
- log.debug("Failed to associate vertex {} to vertex {}, error {}", toscaElementVertex.getUniqueId(), newDataVertex.getUniqueId(), createEdge);
+ log.debug("Failed to associate vertex {} to vertex {}, error {}", toscaElementVertex.getUniqueId(), newDataVertex.getUniqueId(),
+ createEdge);
return Either.right(createEdge);
}
edgeToRemove.remove();
return Either.left(newDataVertex);
}
- public Either<GraphVertex, StorageOperationStatus> associateElementToData(GraphVertex element, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, Map<String, ? extends ToscaDataDefinition> data) {
+ public Either<GraphVertex, StorageOperationStatus> associateElementToData(GraphVertex element, VertexTypeEnum vertexLabel,
+ EdgeLabelEnum edgeLabel,
+ Map<String, ? extends ToscaDataDefinition> data) {
GraphVertex dataV = new GraphVertex(vertexLabel);
String id = IdBuilderUtils.generateChildId(element.getUniqueId(), vertexLabel);
dataV.setUniqueId(id);
@@ -358,9 +359,7 @@ public abstract class BaseOperation {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createVertex.right().value()));
}
dataV = createVertex.left().value();
- JanusGraphOperationStatus
- createEdgeStatus = janusGraphDao
- .createEdge(element.getVertex(), dataV.getVertex(), edgeLabel, new HashMap<>());
+ JanusGraphOperationStatus createEdgeStatus = janusGraphDao.createEdge(element.getVertex(), dataV.getVertex(), edgeLabel, new HashMap<>());
if (createEdgeStatus != JanusGraphOperationStatus.OK) {
log.trace("Failed to create {} vertex for type node {}", vertexLabel, element.getUniqueId());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdgeStatus));
@@ -378,8 +377,9 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, T toscaData,
+ JsonPresentationFields mapKeyField) {
List<T> toscaDataList = new ArrayList<>();
toscaDataList.add(toscaData);
return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField);
@@ -396,9 +396,11 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys,
- JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel,
+ List<T> toscaDataList, List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, false);
}
@@ -412,7 +414,9 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) {
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, T toscaData,
+ JsonPresentationFields mapKeyField) {
List<T> toscaDataList = new ArrayList<>();
toscaDataList.add(toscaData);
return updateToscaDataOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField);
@@ -429,8 +433,11 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys,
- JsonPresentationFields mapKeyField) {
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementOfToscaElement(GraphVertex toscaElement,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, T toscaData,
+ List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
List<T> toscaDataList = new ArrayList<>();
toscaDataList.add(toscaData);
return updateToscaDataDeepElementsOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
@@ -447,9 +454,12 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys,
- JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(GraphVertex toscaElement,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel,
+ List<T> toscaDataList,
+ List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, true);
}
@@ -463,8 +473,9 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, T toscaData,
+ JsonPresentationFields mapKeyField) {
List<T> toscaDataList = new ArrayList<>();
toscaDataList.add(toscaData);
return addToscaDataToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField);
@@ -481,36 +492,44 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys,
- JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementToToscaElement(String toscaElementUid,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, T toscaData,
+ List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
List<T> toscaDataList = new ArrayList<>();
toscaDataList.add(toscaData);
return addToscaDataDeepElementsToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
}
- public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys,
- JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementOfToscaElement(String toscaElementUid,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, T toscaData,
+ List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
List<T> toscaDataList = new ArrayList<>();
toscaDataList.add(toscaData);
return updateToscaDataDeepElementsOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
}
- public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys,
- JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(String toscaElementUid,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel,
+ List<T> toscaDataList,
+ List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
StorageOperationStatus statusRes = null;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) {
- statusRes = updateToscaDataDeepElementsOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
+ statusRes = updateToscaDataDeepElementsOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys,
+ mapKeyField);
}
if (statusRes == null) {
statusRes = StorageOperationStatus.OK;
@@ -518,23 +537,25 @@ public abstract class BaseOperation {
return statusRes;
}
- StorageOperationStatus overrideToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, Map<String, ? extends ToscaDataDefinition> toscaData) {
- return janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse)
- .left()
- .bind(graphVertex -> overrideToscaElementData(graphVertex, toscaData, edgeLabel))
- .either(graphVertex -> StorageOperationStatus.OK,
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ StorageOperationStatus overrideToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel,
+ Map<String, ? extends ToscaDataDefinition> toscaData) {
+ return janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse).left()
+ .bind(graphVertex -> overrideToscaElementData(graphVertex, toscaData, edgeLabel))
+ .either(graphVertex -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
- private Either<GraphVertex, JanusGraphOperationStatus> overrideToscaElementData(GraphVertex toscaElement, Map<String, ? extends ToscaDataDefinition> toscaData, EdgeLabelEnum edgeLabelEnum) {
- return janusGraphDao.getChildVertex(toscaElement, edgeLabelEnum, JsonParseFlagEnum.ParseJson)
- .left()
- .bind(dataVertex -> overrideToscaElementData(dataVertex, toscaElement, toscaData, edgeLabelEnum))
- .right()
- .map(err -> logAndReturn(err, "failed to override tosca data for element {} of type {}. status: {}", toscaElement.getUniqueId(), edgeLabelEnum, err));
+ private Either<GraphVertex, JanusGraphOperationStatus> overrideToscaElementData(GraphVertex toscaElement,
+ Map<String, ? extends ToscaDataDefinition> toscaData,
+ EdgeLabelEnum edgeLabelEnum) {
+ return janusGraphDao.getChildVertex(toscaElement, edgeLabelEnum, JsonParseFlagEnum.ParseJson).left()
+ .bind(dataVertex -> overrideToscaElementData(dataVertex, toscaElement, toscaData, edgeLabelEnum)).right().map(
+ err -> logAndReturn(err, "failed to override tosca data for element {} of type {}. status: {}", toscaElement.getUniqueId(),
+ edgeLabelEnum, err));
}
- private Either<GraphVertex, JanusGraphOperationStatus> overrideToscaElementData(GraphVertex dataElement, GraphVertex toscaElement, Map<String, ? extends ToscaDataDefinition> toscaData, EdgeLabelEnum edgeLabelEnum) {
+ private Either<GraphVertex, JanusGraphOperationStatus> overrideToscaElementData(GraphVertex dataElement, GraphVertex toscaElement,
+ Map<String, ? extends ToscaDataDefinition> toscaData,
+ EdgeLabelEnum edgeLabelEnum) {
dataElement.setJson(toscaData);
return updateOrCopyOnUpdate(dataElement, toscaElement, edgeLabelEnum);
}
@@ -550,20 +571,23 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys,
- JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(String toscaElementUid,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel,
+ List<T> toscaDataList, List<String> pathKeys,
+ JsonPresentationFields mapKeyField) {
StorageOperationStatus statusRes = null;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) {
- statusRes = addToscaDataDeepElementsToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
+ statusRes = addToscaDataDeepElementsToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys,
+ mapKeyField);
}
if (statusRes == null) {
statusRes = StorageOperationStatus.OK;
@@ -571,15 +595,17 @@ public abstract class BaseOperation {
return statusRes;
}
- public <T extends ToscaDataDefinition> StorageOperationStatus deleteToscaDataDeepElementsBlockOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus deleteToscaDataDeepElementsBlockOfToscaElement(String toscaElementUid,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel,
+ String key) {
StorageOperationStatus statusRes = null;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
if (statusRes == null) {
@@ -591,15 +617,18 @@ public abstract class BaseOperation {
return statusRes;
}
- public <T extends ToscaDataDefinition> StorageOperationStatus deleteToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus deleteToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel,
+ String key) {
StorageOperationStatus result = null;
GraphVertex toscaDataVertex = null;
Either<GraphVertex, JanusGraphOperationStatus> toscaDataVertexRes = janusGraphDao
.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
if (toscaDataVertexRes.isRight()) {
JanusGraphOperationStatus status = toscaDataVertexRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS,
+ toscaElement.getUniqueId(), edgeLabel, status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value());
}
if (result == null) {
@@ -610,7 +639,9 @@ public abstract class BaseOperation {
Either<GraphVertex, JanusGraphOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel);
if (updateOrCopyRes.isRight()) {
JanusGraphOperationStatus status = updateOrCopyRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca data block {} from the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca data block {} from the tosca element {}. Status is {}. ",
+ edgeLabel, toscaElement.getUniqueId(), status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
}
@@ -621,15 +652,18 @@ public abstract class BaseOperation {
}
@SuppressWarnings("rawtypes")
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(String toscaElementUid,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel,
+ MapDataDefinition toscaDataMap,
+ String key) {
StorageOperationStatus statusRes = null;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
if (statusRes == null && toscaDataMap != null) {
@@ -642,28 +676,33 @@ public abstract class BaseOperation {
}
@SuppressWarnings("rawtypes")
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel,
+ MapDataDefinition toscaDataMap,
+ String key) {
StorageOperationStatus result = null;
GraphVertex toscaDataVertex = null;
Either<GraphVertex, JanusGraphOperationStatus> toscaDataVertexRes = janusGraphDao
.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
JanusGraphOperationStatus status = toscaDataVertexRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS,
+ toscaElement.getUniqueId(), edgeLabel, status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value());
}
if (result == null && toscaDataVertexRes.isLeft()) {
- toscaDataVertex = toscaDataVertexRes.left().value();
- result = addDeepElementsBlock(toscaDataVertex, toscaDataMap, key);
-
+ toscaDataVertex = toscaDataVertexRes.left().value();
+ result = addDeepElementsBlock(toscaDataVertex, toscaDataMap, key);
}
if (result == null) {
if (toscaDataVertex != null) {
Either<GraphVertex, JanusGraphOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel);
if (updateOrCopyRes.isRight()) {
JanusGraphOperationStatus status = updateOrCopyRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel,
+ toscaElement.getUniqueId(), status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
} else {
@@ -672,7 +711,8 @@ public abstract class BaseOperation {
Either<GraphVertex, StorageOperationStatus> createRes = associateElementToData(toscaElement, vertexLabel, edgeLabel, data);
if (createRes.isRight()) {
StorageOperationStatus status = createRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ",
+ edgeLabel, toscaElement.getUniqueId(), status);
result = status;
}
}
@@ -684,33 +724,37 @@ public abstract class BaseOperation {
}
/**
- *
* @param toscaElementId the id of the tosca element data container
- * @param edgeLabel the edge label of the data type to update
- * @param toscaDataMap the data to update
- * @param key the key in the json object where the map object block resides
+ * @param edgeLabel the edge label of the data type to update
+ * @param toscaDataMap the data to update
+ * @param key the key in the json object where the map object block resides
* @return the status of the update operation
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(String toscaElementId, EdgeLabelEnum edgeLabel, MapDataDefinition<T> toscaDataMap, String key) {
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(String toscaElementId,
+ EdgeLabelEnum edgeLabel,
+ MapDataDefinition<T> toscaDataMap,
+ String key) {
return janusGraphDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse)
- .either(toscaElement -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, edgeLabel, toscaDataMap, key),
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .either(toscaElement -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, edgeLabel, toscaDataMap, key),
+ DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
- private <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, MapDataDefinition<T> toscaDataMap, String key) {
- return janusGraphDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson)
- .left()
- .bind(dataVertex -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, dataVertex, edgeLabel, toscaDataMap, key))
- .either(updatedVertex -> StorageOperationStatus.OK,
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ private <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement,
+ EdgeLabelEnum edgeLabel,
+ MapDataDefinition<T> toscaDataMap,
+ String key) {
+ return janusGraphDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson).left()
+ .bind(dataVertex -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, dataVertex, edgeLabel, toscaDataMap, key))
+ .either(updatedVertex -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
- private <T extends ToscaDataDefinition> Either<GraphVertex, JanusGraphOperationStatus> updateToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, GraphVertex dataElement, EdgeLabelEnum edgeLabel, MapDataDefinition<T> toscaDataMap, String key) {
+ private <T extends ToscaDataDefinition> Either<GraphVertex, JanusGraphOperationStatus> updateToscaDataDeepElementsBlockToToscaElement(
+ GraphVertex toscaElement, GraphVertex dataElement, EdgeLabelEnum edgeLabel, MapDataDefinition<T> toscaDataMap, String key) {
Map<String, T> mapToscaDataDefinition = toscaDataMap.getMapToscaDataDefinition();
updateDeepElements(dataElement, mapToscaDataDefinition, Collections.singletonList(key));
- return updateOrCopyOnUpdate(dataElement, toscaElement, edgeLabel)
- .right()
- .map(err -> logAndReturn(err, "failed while trying to update data vertex from tosca element {}, of type {} . status {}", toscaElement.getUniqueId(), edgeLabel, err));
+ return updateOrCopyOnUpdate(dataElement, toscaElement, edgeLabel).right().map(
+ err -> logAndReturn(err, "failed while trying to update data vertex from tosca element {}, of type {} . status {}",
+ toscaElement.getUniqueId(), edgeLabel, err));
}
/**
@@ -723,8 +767,9 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, T toscaData,
+ JsonPresentationFields mapKeyField) {
List<T> toscaDataList = new ArrayList<>();
toscaDataList.add(toscaData);
return updateToscaDataOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField);
@@ -740,15 +785,16 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, List<T> toscaDataList,
+ JsonPresentationFields mapKeyField) {
StorageOperationStatus statusRes = null;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) {
@@ -770,15 +816,16 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, List<T> toscaDataList,
+ JsonPresentationFields mapKeyField) {
StorageOperationStatus statusRes = null;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) {
@@ -800,9 +847,11 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaDataMap, JsonPresentationFields mapKeyField) {
-
- return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), mapKeyField);
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, Map<String, T> toscaDataMap,
+ JsonPresentationFields mapKeyField) {
+ return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()),
+ mapKeyField);
}
/**
@@ -815,8 +864,9 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, List<T> toscaDataList,
+ JsonPresentationFields mapKeyField) {
return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, false);
}
@@ -830,24 +880,21 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) {
-
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, List<T> toscaDataList,
+ JsonPresentationFields mapKeyField) {
return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, true);
}
public boolean hasEdgeOfType(GraphVertex toscaElement, EdgeLabelEnum edgeLabel) {
- Either<GraphVertex, JanusGraphOperationStatus> vertex = janusGraphDao
- .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
+ Either<GraphVertex, JanusGraphOperationStatus> vertex = janusGraphDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
return vertex.isLeft();
}
@SuppressWarnings("unchecked")
- private <T extends ToscaDataDefinition> StorageOperationStatus updateOrAddToscaData(GraphVertex toscaElement,
- EdgeLabelEnum edgeLabel,
- VertexTypeEnum vertexLabel,
- List<T> toscaDataList,
- JsonPresentationFields mapKeyField,
- boolean isUpdate) {
+ private <T extends ToscaDataDefinition> StorageOperationStatus updateOrAddToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, List<T> toscaDataList,
+ JsonPresentationFields mapKeyField, boolean isUpdate) {
StorageOperationStatus result = null;
GraphVertex toscaDataVertex = null;
Map<String, T> existingToscaDataMap = null;
@@ -857,9 +904,8 @@ public abstract class BaseOperation {
.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
JanusGraphOperationStatus status = toscaDataVertexRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
- FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(),
- edgeLabel, status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS,
+ toscaElement.getUniqueId(), edgeLabel, status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value());
}
if (result == null) {
@@ -867,11 +913,11 @@ public abstract class BaseOperation {
toscaDataVertex = toscaDataVertexRes.left().value();
existingToscaDataMap = (Map<String, T>) toscaDataVertex.getJson();
}
-
- validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingToscaDataMap, isUpdate);
+ validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingToscaDataMap, isUpdate);
if (validateRes.isRight()) {
result = validateRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ",
+ toscaElement.getUniqueId(), edgeLabel, result);
}
}
if (result == null) {
@@ -882,14 +928,16 @@ public abstract class BaseOperation {
result = StorageOperationStatus.OK;
}
return result;
-
}
- <T extends ToscaDataDefinition> StorageOperationStatus updateFullToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaData) {
- Either<GraphVertex, JanusGraphOperationStatus> toscaDataVertexRes = janusGraphDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
+ <T extends ToscaDataDefinition> StorageOperationStatus updateFullToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel, Map<String, T> toscaData) {
+ Either<GraphVertex, JanusGraphOperationStatus> toscaDataVertexRes = janusGraphDao
+ .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
JanusGraphOperationStatus status = toscaDataVertexRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS,
+ toscaElement.getUniqueId(), edgeLabel, status);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value());
}
GraphVertex toscaDataVertex = null;
@@ -900,10 +948,13 @@ public abstract class BaseOperation {
return result == null ? StorageOperationStatus.OK : result;
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private <T, K extends ToscaDataDefinition> StorageOperationStatus updateOrAddToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<K> toscaDataList, List<String> pathKeys,
- JsonPresentationFields mapKeyField, boolean isUpdate) {
-
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ private <T, K extends ToscaDataDefinition> StorageOperationStatus updateOrAddToscaDataDeepElement(GraphVertex toscaElement,
+ EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexLabel,
+ List<K> toscaDataList, List<String> pathKeys,
+ JsonPresentationFields mapKeyField,
+ boolean isUpdate) {
StorageOperationStatus result = null;
GraphVertex toscaDataVertex = null;
Map<String, K> existingDeepElementsMap = null;
@@ -912,7 +963,8 @@ public abstract class BaseOperation {
.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
JanusGraphOperationStatus status = toscaDataVertexRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS,
+ toscaElement.getUniqueId(), edgeLabel, status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value());
}
if (result == null) {
@@ -923,23 +975,23 @@ public abstract class BaseOperation {
validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingDeepElementsMap, isUpdate);
if (validateRes.isRight()) {
result = validateRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ",
+ toscaElement.getUniqueId(), edgeLabel, result);
}
}
if (result == null) {
updateDeepElements(toscaDataVertex, validateRes.left().value(), pathKeys);
Map<String, K> toscaDataToHandle;
- if(toscaDataVertex == null){
+ if (toscaDataVertex == null) {
toscaDataToHandle = new HashMap<>();
Map<String, K> currMap = toscaDataToHandle;
- for (int i = 1; i < pathKeys.size()-1; ++i) {
+ for (int i = 1; i < pathKeys.size() - 1; ++i) {
currMap.put(pathKeys.get(i), (K) new MapDataDefinition());
currMap = (Map<String, K>) ((MapDataDefinition) currMap).getMapToscaDataDefinition().get(pathKeys.get(i));
}
- toscaDataToHandle.put(pathKeys.get(pathKeys.size()-1), (K) new MapDataDefinition(validateRes.left().value()));
-
+ toscaDataToHandle.put(pathKeys.get(pathKeys.size() - 1), (K) new MapDataDefinition(validateRes.left().value()));
} else {
- toscaDataToHandle = (Map<String, K>) toscaDataVertex.getJson();
+ toscaDataToHandle = (Map<String, K>) toscaDataVertex.getJson();
}
result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaDataToHandle);
}
@@ -949,23 +1001,22 @@ public abstract class BaseOperation {
return result;
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private <T, K extends ToscaDataDefinition> void updateDeepElements(GraphVertex toscaDataVertex, Map<String, K> mergedDeepElementMap, List<String> pathKeys) {
-
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ private <T, K extends ToscaDataDefinition> void updateDeepElements(GraphVertex toscaDataVertex, Map<String, K> mergedDeepElementMap,
+ List<String> pathKeys) {
if (toscaDataVertex != null && MapUtils.isNotEmpty(mergedDeepElementMap)) {
Map<String, MapDataDefinition> currMap = (Map<String, MapDataDefinition>) toscaDataVertex.getJson();
- if(!currMap.containsKey(pathKeys.get(0))){
+ if (!currMap.containsKey(pathKeys.get(0))) {
currMap.put(pathKeys.get(0), new MapDataDefinition<>());
}
MapDataDefinition currDeepElement = currMap.get(pathKeys.get(0));
-
for (int i = 1; i < pathKeys.size(); ++i) {
- if(currDeepElement.findByKey(pathKeys.get(i)) == null){
+ if (currDeepElement.findByKey(pathKeys.get(i)) == null) {
currDeepElement.put(pathKeys.get(i), new MapDataDefinition<>());
}
currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i));
}
- if(currDeepElement != null){
+ if (currDeepElement != null) {
for (Map.Entry<String, K> elementEntry : mergedDeepElementMap.entrySet()) {
currDeepElement.put(elementEntry.getKey(), elementEntry.getValue());
}
@@ -973,7 +1024,7 @@ public abstract class BaseOperation {
}
}
- @SuppressWarnings({ "unchecked", "rawtypes" })
+ @SuppressWarnings({"unchecked", "rawtypes"})
private <T, K extends ToscaDataDefinition> Map<String, K> getDeepElements(GraphVertex toscaDataVertex, List<String> pathKeys) {
Map<String, K> result = null;
Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson();
@@ -981,7 +1032,7 @@ public abstract class BaseOperation {
for (int i = 1; i < pathKeys.size(); ++i) {
currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i));
}
- if(currDeepElement != null){
+ if (currDeepElement != null) {
result = (Map<String, K>) currDeepElement.getMapToscaDataDefinition();
}
return result;
@@ -989,11 +1040,12 @@ public abstract class BaseOperation {
@SuppressWarnings("unchecked")
private <T extends ToscaDataDefinition> StorageOperationStatus addDeepElementsBlock(GraphVertex toscaDataVertex, T toscaDataBlock, String key) {
-
StorageOperationStatus result = null;
Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson();
if (currMap.containsKey(key)) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add block of deep tosca data elements by label {}." + " The block element with the same key {} already exists. ", toscaDataVertex.getLabel(), key);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to add block of deep tosca data elements by label {}." + " The block element with the same key {} already exists. ",
+ toscaDataVertex.getLabel(), key);
result = StorageOperationStatus.ENTITY_ALREADY_EXISTS;
}
if (result == null) {
@@ -1004,11 +1056,12 @@ public abstract class BaseOperation {
@SuppressWarnings("unchecked")
private <T extends ToscaDataDefinition> StorageOperationStatus deleteDeepElementsBlock(GraphVertex toscaDataVertex, String key) {
-
StorageOperationStatus result = null;
Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson();
if (!currMap.containsKey(key)) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete block of deep tosca data elements by label {}." + " The block element with the same key {} doesn't exist. ", toscaDataVertex.getLabel(), key);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to delete block of deep tosca data elements by label {}." + " The block element with the same key {} doesn't exist. ",
+ toscaDataVertex.getLabel(), key);
result = StorageOperationStatus.NOT_FOUND;
}
if (result == null) {
@@ -1026,14 +1079,13 @@ public abstract class BaseOperation {
* @return
*/
public StorageOperationStatus removeToscaData(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) {
-
StorageOperationStatus statusRes = StorageOperationStatus.OK;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
if (statusRes == StorageOperationStatus.OK) {
@@ -1061,7 +1113,8 @@ public abstract class BaseOperation {
.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
if (toscaDataVertexRes.isRight()) {
JanusGraphOperationStatus status = toscaDataVertexRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS,
+ toscaElement.getUniqueId(), edgeLabel, status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value());
}
if (result == null) {
@@ -1069,27 +1122,29 @@ public abstract class BaseOperation {
edges = toscaDataVertex.getVertex().edges(Direction.IN);
if (edges == null || !edges.hasNext()) {
result = StorageOperationStatus.NOT_FOUND;
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, result);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS,
+ toscaElement.getUniqueId(), edgeLabel, result);
}
}
if (result == null) {
- if (edges!=null) {
- while (edges.hasNext()) {
- ++edgeCounter;
- edge = edges.next();
- if (edge.outVertex().id().equals(toscaElement.getVertex().id())) {
- edgeToDelete = edge;
- break;
- }
- }
+ if (edges != null) {
+ while (edges.hasNext()) {
+ ++edgeCounter;
+ edge = edges.next();
+ if (edge.outVertex().id().equals(toscaElement.getVertex().id())) {
+ edgeToDelete = edge;
+ break;
+ }
+ }
}
if (edgeToDelete == null) {
result = StorageOperationStatus.NOT_FOUND;
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, result);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS,
+ toscaElement.getUniqueId(), edgeLabel, result);
}
}
if (result == null) {
- if (edgeCounter > 1 && edgeToDelete!=null) {
+ if (edgeCounter > 1 && edgeToDelete != null) {
edgeToDelete.remove();
} else {
toscaDataVertex.getVertex().remove();
@@ -1110,14 +1165,13 @@ public abstract class BaseOperation {
* @return
*/
public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, List<String> uniqueKeys) {
-
StorageOperationStatus statusRes = StorageOperationStatus.OK;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
if (statusRes == StorageOperationStatus.OK) {
@@ -1136,22 +1190,21 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public StorageOperationStatus deleteToscaDataElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) {
-
+ public StorageOperationStatus deleteToscaDataElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel,
+ String uniqueKey, JsonPresentationFields mapKeyField) {
StorageOperationStatus statusRes = StorageOperationStatus.OK;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
if (statusRes == StorageOperationStatus.OK) {
statusRes = deleteToscaDataElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, mapKeyField);
}
return statusRes;
-
}
/**
@@ -1165,22 +1218,21 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public StorageOperationStatus deleteToscaDataDeepElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List<String> pathKeys, JsonPresentationFields mapKeyField) {
-
+ public StorageOperationStatus deleteToscaDataDeepElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel,
+ String uniqueKey, List<String> pathKeys, JsonPresentationFields mapKeyField) {
StorageOperationStatus statusRes = StorageOperationStatus.OK;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
if (statusRes == StorageOperationStatus.OK) {
statusRes = deleteToscaDataDeepElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, pathKeys, mapKeyField);
}
return statusRes;
-
}
/**
@@ -1194,15 +1246,15 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public StorageOperationStatus deleteToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List<String> pathKeys, JsonPresentationFields mapKeyField) {
-
+ public StorageOperationStatus deleteToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel,
+ String uniqueKey, List<String> pathKeys, JsonPresentationFields mapKeyField) {
List<String> uniqueKeys = new ArrayList<>();
uniqueKeys.add(uniqueKey);
return deleteToscaDataDeepElements(toscaElement, edgeLabel, vertexLabel, uniqueKeys, pathKeys, mapKeyField);
}
- public StorageOperationStatus deleteToscaDataDeepElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, List<String> pathKeys, JsonPresentationFields mapKeyField) {
-
+ public StorageOperationStatus deleteToscaDataDeepElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel,
+ List<String> uniqueKeys, List<String> pathKeys, JsonPresentationFields mapKeyField) {
StorageOperationStatus result = null;
GraphVertex toscaDataVertex;
Map<String, ToscaDataDefinition> existingToscaDataMap = null;
@@ -1210,7 +1262,8 @@ public abstract class BaseOperation {
.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
if (toscaDataVertexRes.isRight()) {
JanusGraphOperationStatus status = toscaDataVertexRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS,
+ toscaElement.getUniqueId(), edgeLabel, status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value());
}
if (result == null) {
@@ -1224,12 +1277,15 @@ public abstract class BaseOperation {
return result;
}
- private StorageOperationStatus deleteElementsFromDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List<String> uniqueKeys, GraphVertex toscaDataVertex, Map<String, ToscaDataDefinition> existingToscaDataMap) {
+ private StorageOperationStatus deleteElementsFromDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List<String> uniqueKeys,
+ GraphVertex toscaDataVertex, Map<String, ToscaDataDefinition> existingToscaDataMap) {
StorageOperationStatus result;
for (String uniqueKey : uniqueKeys) {
result = removeKeyFromDataVertex(uniqueKey, existingToscaDataMap);
if (result != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca data element of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to delete tosca data element of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel,
+ result);
break;
}
}
@@ -1247,8 +1303,8 @@ public abstract class BaseOperation {
* @param mapKeyField
* @return
*/
- public StorageOperationStatus deleteToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) {
-
+ public StorageOperationStatus deleteToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel,
+ String uniqueKey, JsonPresentationFields mapKeyField) {
List<String> uniqueKeys = new ArrayList<>();
uniqueKeys.add(uniqueKey);
return deleteToscaDataElements(toscaElement, edgeLabel, uniqueKeys);
@@ -1270,7 +1326,8 @@ public abstract class BaseOperation {
.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
if (toscaDataVertexRes.isRight()) {
JanusGraphOperationStatus status = toscaDataVertexRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS,
+ toscaElement.getUniqueId(), edgeLabel, status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value());
}
if (result == null) {
@@ -1286,25 +1343,32 @@ public abstract class BaseOperation {
/**
* Adds the map data entry to the graph vertex of the specified type, related with the specified edge to the component specified by ID
- * @param componentId The uniqueId of the component
- * @param vertexTypeEnum The type of the vertex
- * @param edgeLabelEnum The type of the edge
- * @param mapDataEntry The map data entry
- * @param <T extends MapDataDefinition>
- * @return The status of the operation result
+ *
+ * @param componentId The uniqueId of the component
+ * @param vertexTypeEnum The type of the vertex
+ * @param edgeLabelEnum The type of the edge
+ * @param mapDataEntry The map data entry
+ * @param <T extends MapDataDefinition>
+ * @return The status of the operation result
*/
- public <T extends MapDataDefinition> StorageOperationStatus addElementToComponent(String componentId, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map.Entry<String, T> mapDataEntry){
- if(MapUtils.isNotEmpty(mapDataEntry.getValue().getMapToscaDataDefinition()))
- return addToscaDataDeepElementsBlockToToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, mapDataEntry.getValue(), mapDataEntry.getKey());
+ public <T extends MapDataDefinition> StorageOperationStatus addElementToComponent(String componentId, VertexTypeEnum vertexTypeEnum,
+ EdgeLabelEnum edgeLabelEnum,
+ Map.Entry<String, T> mapDataEntry) {
+ if (MapUtils.isNotEmpty(mapDataEntry.getValue().getMapToscaDataDefinition())) {
+ return addToscaDataDeepElementsBlockToToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, mapDataEntry.getValue(),
+ mapDataEntry.getKey());
+ }
return StorageOperationStatus.OK;
}
- private <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex) {
+ private <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel,
+ GraphVertex toscaDataVertex) {
StorageOperationStatus result = StorageOperationStatus.OK;
Either<GraphVertex, JanusGraphOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel);
if (updateOrCopyRes.isRight()) {
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateOrCopyRes.right().value());
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), result);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update tosca data {} of the tosca element {}. Status is {}. ", edgeLabel,
+ toscaElement.getUniqueId(), result);
}
return result;
}
@@ -1318,7 +1382,8 @@ public abstract class BaseOperation {
}
<K extends ToscaDataDefinition> StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel,
- EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map<String, K> mergedToscaDataMap) {
+ EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex,
+ Map<String, K> mergedToscaDataMap) {
StorageOperationStatus result = StorageOperationStatus.OK;
if (toscaDataVertex == null) {
if (MapUtils.isEmpty(mergedToscaDataMap)) {
@@ -1328,7 +1393,9 @@ public abstract class BaseOperation {
Either<GraphVertex, StorageOperationStatus> createRes = associateElementToData(toscaElement, vertexLabel, edgeLabel, mergedToscaDataMap);
if (createRes.isRight()) {
StorageOperationStatus status = createRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel,
+ toscaElement.getUniqueId(), status);
result = status;
}
} else {
@@ -1340,16 +1407,20 @@ public abstract class BaseOperation {
Either<GraphVertex, JanusGraphOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel);
if (updateOrCopyRes.isRight()) {
JanusGraphOperationStatus status = updateOrCopyRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel,
+ toscaElement.getUniqueId(), status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
}
return result;
}
- private <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> validateMergeToscaData(GraphVertex toscaElement, List<T> toscaDataList, JsonPresentationFields mapKeyField, Map<String, T> existingToscaDataMap,
- boolean isUpdate) {
-
+ private <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> validateMergeToscaData(GraphVertex toscaElement,
+ List<T> toscaDataList,
+ JsonPresentationFields mapKeyField,
+ Map<String, T> existingToscaDataMap,
+ boolean isUpdate) {
Map<String, T> mergedToscaDataMap = new HashMap<>();
StorageOperationStatus status;
Either<Map<String, T>, StorageOperationStatus> result = Either.left(mergedToscaDataMap);
@@ -1366,37 +1437,39 @@ public abstract class BaseOperation {
return result;
}
- private <T extends ToscaDataDefinition> StorageOperationStatus handleToscaDataElement(GraphVertex toscaElement, JsonPresentationFields mapKeyField, Map<String, T> mergedToscaDataMap, T toscaDataElement, boolean isUpdate) {
-
+ private <T extends ToscaDataDefinition> StorageOperationStatus handleToscaDataElement(GraphVertex toscaElement,
+ JsonPresentationFields mapKeyField,
+ Map<String, T> mergedToscaDataMap, T toscaDataElement,
+ boolean isUpdate) {
StorageOperationStatus status = StorageOperationStatus.OK;
String currKey = (String) toscaDataElement.getToscaPresentationValue(mapKeyField);
-
- if(StringUtils.isEmpty(currKey) && toscaDataElement instanceof ListDataDefinition) {
+ if (StringUtils.isEmpty(currKey) && toscaDataElement instanceof ListDataDefinition) {
ToscaDataDefinition toscaDataDefinition = ((ListDataDefinition<? extends ToscaDataDefinition>) toscaDataElement)
- .getListToscaDataDefinition().get(0);
- if(toscaDataDefinition != null) {
- currKey = (String) toscaDataDefinition.getToscaPresentationValue(mapKeyField);
+ .getListToscaDataDefinition().get(0);
+ if (toscaDataDefinition != null) {
+ currKey = (String) toscaDataDefinition.getToscaPresentationValue(mapKeyField);
}
}
-
if (StringUtils.isEmpty(currKey)) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The key is empty. ");
status = StorageOperationStatus.BAD_REQUEST;
} else if (!isUpdate && mergedToscaDataMap.containsKey(currKey)) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The element with the same key {} already exists. ", toscaElement.getUniqueId(), currKey);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to add tosca data to tosca element {}. The element with the same key {} already exists. ", toscaElement.getUniqueId(),
+ currKey);
status = StorageOperationStatus.BAD_REQUEST;
}
mergedToscaDataMap.put(currKey, toscaDataElement);
return status;
}
- protected GroupInstanceDataDefinition buildGroupInstanceDataDefinition(GroupDataDefinition group, ComponentInstanceDataDefinition componentInstance, Map<String, ArtifactDataDefinition> instDeplArtifMap) {
-
+ protected GroupInstanceDataDefinition buildGroupInstanceDataDefinition(GroupDataDefinition group,
+ ComponentInstanceDataDefinition componentInstance,
+ Map<String, ArtifactDataDefinition> instDeplArtifMap) {
String componentInstanceName = componentInstance.getName();
Long creationDate = System.currentTimeMillis();
GroupInstanceDataDefinition groupInstance = new GroupInstanceDataDefinition();
String groupUid = group.getUniqueId();
-
groupInstance.setGroupUid(groupUid);
groupInstance.setType(group.getType());
groupInstance.setCustomizationUUID(generateCustomizationUUID());
@@ -1405,19 +1478,17 @@ public abstract class BaseOperation {
groupInstance.setName(buildGroupInstanceName(componentInstanceName, group.getName()));
groupInstance.setGroupName(group.getName());
groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstance.getName()));
- groupInstance.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentInstance.getUniqueId(), groupUid, groupInstance.getNormalizedName()));
+ groupInstance
+ .setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentInstance.getUniqueId(), groupUid, groupInstance.getNormalizedName()));
groupInstance.setArtifacts(group.getArtifacts());
-
groupInstance.setArtifactsUuid(group.getArtifactsUuid());
groupInstance.setProperties(group.getProperties());
convertPropertiesToInstanceProperties(groupInstance.getProperties());
groupInstance.setInvariantUUID(group.getInvariantUUID());
groupInstance.setGroupUUID(group.getGroupUUID());
groupInstance.setVersion(group.getVersion());
-
return groupInstance;
- }
-
+ }
protected String buildGroupInstanceName(String instanceName, String groupName) {
return ValidationUtils.normalizeComponentInstanceName(instanceName) + ".." + groupName;
@@ -1427,16 +1498,16 @@ public abstract class BaseOperation {
return UUID.randomUUID().toString();
}
- protected void convertPropertiesToInstanceProperties(List<PropertyDataDefinition> properties){
+ protected void convertPropertiesToInstanceProperties(List<PropertyDataDefinition> properties) {
properties.forEach(PropertyDataDefinition::convertPropertyDataToInstancePropertyData);
}
- private JanusGraphOperationStatus logAndReturn(JanusGraphOperationStatus janusGraphOperationStatus, String logMsg, Object ... logParams) {
+ private JanusGraphOperationStatus logAndReturn(JanusGraphOperationStatus janusGraphOperationStatus, String logMsg, Object... logParams) {
log.debug(logMsg, logParams);
return janusGraphOperationStatus;
}
- protected GraphVertex throwStorageException(JanusGraphOperationStatus status) {
+ protected GraphVertex throwStorageException(JanusGraphOperationStatus status) {
throw new StorageException(status);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ByToscaNameDerivedNodeTypeResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ByToscaNameDerivedNodeTypeResolver.java
index 9b9a3e6799..743fcdec44 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ByToscaNameDerivedNodeTypeResolver.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ByToscaNameDerivedNodeTypeResolver.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.jsonjanusgraph.operations;
import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
@@ -32,10 +34,6 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
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("derived-resource-resolver")
public class ByToscaNameDerivedNodeTypeResolver implements DerivedNodeTypeResolver {
@@ -46,10 +44,7 @@ public class ByToscaNameDerivedNodeTypeResolver implements DerivedNodeTypeResolv
public Either<List<GraphVertex>, JanusGraphOperationStatus> findDerivedResources(String parentResource) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
-
propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, parentResource);
-
- return janusGraphDao
- .getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
+ return janusGraphDao.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperation.java
index 3b544aaa39..65673345e7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CapabilitiesOperation.java
@@ -13,10 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
@@ -38,15 +41,16 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
@org.springframework.stereotype.Component("capabilities-operation")
public class CapabilitiesOperation extends BaseOperation {
+
private static final Logger LOGGER = LoggerFactory.getLogger(CapabilitiesOperation.class);
+ private static ListCapabilityDataDefinition convertToListCapabilityDataDefinition(List<CapabilityDefinition> capabilities) {
+ List<CapabilityDataDefinition> capabilityDefinitions = new ArrayList<>(capabilities);
+ return new ListCapabilityDataDefinition(capabilityDefinitions);
+ }
+
public Either<List<CapabilityDefinition>, StorageOperationStatus> addCapabilities(String componentId,
List<CapabilityDefinition> capabilityDefinitions) {
return addOrUpdateCapabilities(componentId, capabilityDefinitions, false);
@@ -60,89 +64,71 @@ public class CapabilitiesOperation extends BaseOperation {
private Either<List<CapabilityDefinition>, StorageOperationStatus> addOrUpdateCapabilities(String componentId,
List<CapabilityDefinition> capabilityDefinitions,
boolean isUpdateAction) {
- StorageOperationStatus statusRes = performUpdateToscaAction(isUpdateAction,
- componentId, Collections.singletonList(convertToListCapabilityDataDefinition(capabilityDefinitions)));
+ StorageOperationStatus statusRes = performUpdateToscaAction(isUpdateAction, componentId,
+ Collections.singletonList(convertToListCapabilityDataDefinition(capabilityDefinitions)));
if (!statusRes.equals(StorageOperationStatus.OK)) {
- LOGGER.error("Failed to find the parent capability of capability type {}." + " status is {}", componentId,
- statusRes);
+ LOGGER.error("Failed to find the parent capability of capability type {}." + " status is {}", componentId, statusRes);
return Either.right(statusRes);
}
return Either.left(capabilityDefinitions);
}
public StorageOperationStatus deleteCapabilities(Component component, String capabilityIdToDelete) {
- return deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.CAPABILITIES,
- Collections.singletonList(capabilityIdToDelete));
+ return deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.CAPABILITIES, Collections.singletonList(capabilityIdToDelete));
}
public StorageOperationStatus deleteCapabilityProperties(Component component, String capabilityPropIdToDelete) {
return deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.CAPABILITIES_PROPERTIES,
- Collections.singletonList(capabilityPropIdToDelete));
- }
-
- private static ListCapabilityDataDefinition convertToListCapabilityDataDefinition(List<CapabilityDefinition> capabilities) {
- List<CapabilityDataDefinition> capabilityDefinitions = new ArrayList<>(capabilities);
- return new ListCapabilityDataDefinition(capabilityDefinitions);
+ Collections.singletonList(capabilityPropIdToDelete));
}
- private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, String componentId,
- List<ListCapabilityDataDefinition> toscaDataList) {
+ private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, String componentId, List<ListCapabilityDataDefinition> toscaDataList) {
if (isUpdate) {
- return updateToscaDataOfToscaElement(componentId, EdgeLabelEnum.CAPABILITIES,
- VertexTypeEnum.CAPABILITIES, toscaDataList, JsonPresentationFields.TYPE);
+ return updateToscaDataOfToscaElement(componentId, EdgeLabelEnum.CAPABILITIES, VertexTypeEnum.CAPABILITIES, toscaDataList,
+ JsonPresentationFields.TYPE);
} else {
- return addToscaDataToToscaElement(componentId, EdgeLabelEnum.CAPABILITIES,
- VertexTypeEnum.CAPABILITIES, toscaDataList, JsonPresentationFields.TYPE);
+ return addToscaDataToToscaElement(componentId, EdgeLabelEnum.CAPABILITIES, VertexTypeEnum.CAPABILITIES, toscaDataList,
+ JsonPresentationFields.TYPE);
}
}
private StorageOperationStatus createOrUpdateCapabilityProperties(String componentId, TopologyTemplate toscaElement,
Map<String, MapPropertiesDataDefinition> propertiesMap) {
- GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum
- .NoParse)
- .left().on(this::throwStorageException);
+ GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).left().on(this::throwStorageException);
Map<String, MapPropertiesDataDefinition> capabilitiesProperties = toscaElement.getCapabilitiesProperties();
- if(MapUtils.isNotEmpty(capabilitiesProperties)) {
-
+ if (MapUtils.isNotEmpty(capabilitiesProperties)) {
capabilitiesProperties.forEach((key, val) -> {
Map<String, PropertyDataDefinition> mapToscaDataDefinition = val.getMapToscaDataDefinition();
mapToscaDataDefinition.forEach((key1, val1) -> {
-
propertiesMap.forEach((propKey, propVal) -> {
Map<String, PropertyDataDefinition> propValMapToscaDataDefinition = propVal.getMapToscaDataDefinition();
propValMapToscaDataDefinition.forEach((propKey1, propVal1) -> {
- if(propKey1.equals(key1) && val1.getUniqueId().equals(propVal1.getUniqueId())) {
+ if (propKey1.equals(key1) && val1.getUniqueId().equals(propVal1.getUniqueId())) {
ToscaDataDefinition.mergeDataMaps(mapToscaDataDefinition, propValMapToscaDataDefinition);
}
});
});
});
});
-
ToscaDataDefinition.mergeDataMaps(propertiesMap, capabilitiesProperties);
}
-
- return topologyTemplateOperation.updateFullToscaData(toscaElementV,
- EdgeLabelEnum.CAPABILITIES_PROPERTIES, VertexTypeEnum.CAPABILITIES_PROPERTIES, propertiesMap);
+ return topologyTemplateOperation
+ .updateFullToscaData(toscaElementV, EdgeLabelEnum.CAPABILITIES_PROPERTIES, VertexTypeEnum.CAPABILITIES_PROPERTIES, propertiesMap);
}
- public StorageOperationStatus createOrUpdateCapabilityProperties(String componentId,
- Map<String, MapPropertiesDataDefinition> propertiesMap) {
+ public StorageOperationStatus createOrUpdateCapabilityProperties(String componentId, Map<String, MapPropertiesDataDefinition> propertiesMap) {
StorageOperationStatus propertiesStatusRes = null;
- if(MapUtils.isNotEmpty(propertiesMap)) {
- propertiesStatusRes = createOrUpdateCapabilityProperties(componentId, getTopologyTemplate(componentId),
- propertiesMap);
+ if (MapUtils.isNotEmpty(propertiesMap)) {
+ propertiesStatusRes = createOrUpdateCapabilityProperties(componentId, getTopologyTemplate(componentId), propertiesMap);
}
-
return propertiesStatusRes;
}
private TopologyTemplate getTopologyTemplate(String componentId) {
- return (TopologyTemplate)topologyTemplateOperation
- .getToscaElement(componentId, getFilterComponentWithCapProperties())
- .left()
- .on(this::throwStorageException);
+ return (TopologyTemplate) topologyTemplateOperation.getToscaElement(componentId, getFilterComponentWithCapProperties()).left()
+ .on(this::throwStorageException);
}
+
private ComponentParametersView getFilterComponentWithCapProperties() {
ComponentParametersView filter = new ComponentParametersView();
filter.setIgnoreCapabiltyProperties(false);
@@ -152,5 +138,4 @@ public class CapabilitiesOperation extends BaseOperation {
private ToscaElement throwStorageException(StorageOperationStatus status) {
throw new StorageException(status);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java
index 15ef5e32dc..1c5cb9707d 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.jsonjanusgraph.operations;
import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
@@ -33,33 +35,25 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
@org.springframework.stereotype.Component("category-operation")
-public class CategoryOperation extends BaseOperation{
+public class CategoryOperation extends BaseOperation {
private static final Logger log = Logger.getLogger(CategoryOperation.class.getName());
/**
- *
* @param name
* @param type
* @return
*/
- public Either<GraphVertex, StorageOperationStatus> getCategory(String name, VertexTypeEnum type) {
+ public Either<GraphVertex, StorageOperationStatus> getCategory(String name, VertexTypeEnum type) {
if (name != null) {
String categoryUid = UniqueIdBuilder.buildComponentCategoryUid(name, type);
Map<GraphPropertyEnum, Object> props = new HashMap<>();
props.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(name));
- Either<List<GraphVertex>, JanusGraphOperationStatus> either = janusGraphDao
- .getByCriteria(type, props);
-
+ Either<List<GraphVertex>, JanusGraphOperationStatus> either = janusGraphDao.getByCriteria(type, props);
if (either.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = either.right().value();
- log.debug("Problem while geting category with id {}. reason - {}", categoryUid, janusGraphOperationStatus
- .name());
+ log.debug("Problem while geting category with id {}. reason - {}", categoryUid, janusGraphOperationStatus.name());
if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) {
return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
} else {
@@ -71,20 +65,21 @@ public class CategoryOperation extends BaseOperation{
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
}
+
/**
- *
* @param categoryV
* @param name
* @return
*/
- public Either<GraphVertex, StorageOperationStatus> getSubCategoryForCategory(GraphVertex categoryV, String name ) {
- Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = janusGraphDao.getChildrenVertices(categoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
- if ( childrenVertecies.isRight() ){
+ public Either<GraphVertex, StorageOperationStatus> getSubCategoryForCategory(GraphVertex categoryV, String name) {
+ Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = janusGraphDao
+ .getChildrenVertices(categoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
+ if (childrenVertecies.isRight()) {
log.debug("Failed to fetch children verticies for category {} error {}", categoryV.getUniqueId(), childrenVertecies.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value()));
}
- for ( GraphVertex childV : childrenVertecies.left().value() ){
- if ( childV.getMetadataProperty(GraphPropertyEnum.NAME).equals(name) ){
+ for (GraphVertex childV : childrenVertecies.left().value()) {
+ if (childV.getMetadataProperty(GraphPropertyEnum.NAME).equals(name)) {
return Either.left(childV);
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java
index 8dc1336d07..dd21ccf2df 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
+import static java.util.Collections.emptyMap;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
@@ -34,14 +39,6 @@ import org.openecomp.sdc.be.model.operations.impl.OperationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import static java.util.Collections.emptyMap;
-
/**
* Created by yavivi on 26/01/2018.
*/
@@ -50,60 +47,55 @@ public class ExternalReferencesOperation extends BaseOperation {
@Autowired
private IdMapper idMapper;
-
@Autowired
private OperationUtils operationUtils;
-
/**
* Constructor
*/
- public ExternalReferencesOperation(JanusGraphDao janusGraphDao, NodeTypeOperation nto, TopologyTemplateOperation tto, IdMapper idMapper){
+ public ExternalReferencesOperation(JanusGraphDao janusGraphDao, NodeTypeOperation nto, TopologyTemplateOperation tto, IdMapper idMapper) {
this.janusGraphDao = janusGraphDao;
this.topologyTemplateOperation = tto;
this.nodeTypeOperation = nto;
this.idMapper = idMapper;
}
- public Either<String, ActionStatus> addExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType, String reference) {
+ public Either<String, ActionStatus> addExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType,
+ String reference) {
Either<String, ActionStatus> addResult = addExternalReference(serviceUuid, componentInstanceName, objectType, reference);
janusGraphDao.commit();
return addResult;
}
- public Either<String, ActionStatus> deleteExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType, String reference) {
+ public Either<String, ActionStatus> deleteExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType,
+ String reference) {
Either<String, ActionStatus> result = deleteExternalReference(serviceUuid, componentInstanceName, objectType, reference);
janusGraphDao.commit();
return result;
}
- public Either<String, ActionStatus> updateExternalReferenceWithCommit(String serviceVertexUuid, String componentInstanceName, String objectType, String oldRef, String newRef) {
+ public Either<String, ActionStatus> updateExternalReferenceWithCommit(String serviceVertexUuid, String componentInstanceName, String objectType,
+ String oldRef, String newRef) {
Either<String, ActionStatus> updateResult = updateExternalReference(serviceVertexUuid, componentInstanceName, objectType, oldRef, newRef);
janusGraphDao.commit();
return updateResult;
}
public Either<String, ActionStatus> addExternalReference(String assetUuid, String componentInstanceName, String objectType, String reference) {
-
//Get Container vertex
Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(assetUuid);
- if (vertexById.isRight()){
+ if (vertexById.isRight()) {
return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
}
-
GraphVertex serviceVertex = vertexById.left().value();
-
final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex);
if (compInstanceUniqueId == null) {
return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
}
-
//Get the external references map vertex
final Either<GraphVertex, JanusGraphOperationStatus> dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
-
//Check whether data vertex found
GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null;
-
//instanceId -> externalRefsMap
Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData;
if (externalRefsVertex == null) {
@@ -114,40 +106,35 @@ public class ExternalReferencesOperation extends BaseOperation {
externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
externalReferencesFullData.computeIfAbsent(compInstanceUniqueId, k -> new MapComponentInstanceExternalRefs());
}
-
boolean isAdded = addExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference);
updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData);
-
return isAdded ? Either.left(reference) : Either.right(ActionStatus.EXT_REF_ALREADY_EXIST);
}
- public Either<String, ActionStatus> deleteExternalReference(String assetUuid, String componentInstanceName, String objectType, String reference){
+ public Either<String, ActionStatus> deleteExternalReference(String assetUuid, String componentInstanceName, String objectType, String reference) {
//Get Service vertex
Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(assetUuid);
- if (vertexById.isRight()){
+ if (vertexById.isRight()) {
return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
}
GraphVertex serviceVertex = vertexById.left().value();
-
final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex);
if (compInstanceUniqueId == null) {
return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
}
-
//Get the external references map vertex
final Either<GraphVertex, JanusGraphOperationStatus> dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
-
//Check whether data vertex found
GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null;
boolean refDeleted = false;
if (externalRefsVertex != null) {
- Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
+ Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex
+ .getJson();
if (externalReferencesFullData != null) {
refDeleted = deleteExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference);
updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData);
}
}
-
if (refDeleted) {
return Either.left(reference);
} else {
@@ -155,29 +142,27 @@ public class ExternalReferencesOperation extends BaseOperation {
}
}
- public Either<String, ActionStatus> updateExternalReference(String assetUuid, String componentInstanceName, String objectType, String oldRef, String newRef) {
+ public Either<String, ActionStatus> updateExternalReference(String assetUuid, String componentInstanceName, String objectType, String oldRef,
+ String newRef) {
//Get Service vertex
Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(assetUuid);
- if (vertexById.isRight()){
+ if (vertexById.isRight()) {
return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
}
-
GraphVertex serviceVertex = vertexById.left().value();
-
//Map instance_name -> uuid
final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex);
if (compInstanceUniqueId == null) {
return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
}
-
//Get the external references map vertex
final Either<GraphVertex, JanusGraphOperationStatus> dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
-
//Check whether data vertex found
GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null;
boolean refReplaced = false;
if (externalRefsVertex != null) {
- Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
+ Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex
+ .getJson();
if (externalReferencesFullData != null) {
refReplaced = updateExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, oldRef, newRef);
updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData);
@@ -193,29 +178,25 @@ public class ExternalReferencesOperation extends BaseOperation {
public Either<Map<String, List<String>>, ActionStatus> getExternalReferences(String assetUuid, String objectType) {
//Get Service vertex
Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(assetUuid);
- if (vertexById.isRight()){
+ if (vertexById.isRight()) {
return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
}
-
GraphVertex serviceVertex = vertexById.left().value();
-
Map<String, List<String>> result = new HashMap();
-
//Get the external references map vertex
final Either<GraphVertex, JanusGraphOperationStatus> dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
//Check whether data vertex found
GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null;
if (externalRefsVertex != null) {
- Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
+ Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex
+ .getJson();
if (externalReferencesFullData != null) {
- externalReferencesFullData.entrySet().forEach(
- s -> {
- List<String> externalRefsByObjectType = externalReferencesFullData.get(s.getKey()).getExternalRefsByObjectType(objectType);
- List<String> refList = externalRefsByObjectType == null ? new ArrayList<>() : externalRefsByObjectType;
- String key = idMapper.mapUniqueIdToComponentNameTo(s.getKey(), serviceVertex);
- result.put(key, refList);
- }
- );
+ externalReferencesFullData.entrySet().forEach(s -> {
+ List<String> externalRefsByObjectType = externalReferencesFullData.get(s.getKey()).getExternalRefsByObjectType(objectType);
+ List<String> refList = externalRefsByObjectType == null ? new ArrayList<>() : externalRefsByObjectType;
+ String key = idMapper.mapUniqueIdToComponentNameTo(s.getKey(), serviceVertex);
+ result.put(key, refList);
+ });
return Either.left(result);
}
}
@@ -223,13 +204,9 @@ public class ExternalReferencesOperation extends BaseOperation {
return Either.left(new HashMap<>());
}
- public void addAllExternalReferences(String containerUniqueId,
- String compInstanceUniqueId,
+ public void addAllExternalReferences(String containerUniqueId, String compInstanceUniqueId,
Map<String, List<String>> instanceExternalReferences) {
-
- GraphVertex serviceVertex = janusGraphDao.getVertexById(containerUniqueId)
- .left()
- .on(operationUtils::onJanusGraphOperationFailure);
+ GraphVertex serviceVertex = janusGraphDao.getVertexById(containerUniqueId).left().on(operationUtils::onJanusGraphOperationFailure);
Either<GraphVertex, JanusGraphOperationStatus> dataVertex = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData;
if (dataVertex.isLeft()) {
@@ -241,22 +218,18 @@ public class ExternalReferencesOperation extends BaseOperation {
updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData);
}
- public Map<String, List<String>> getAllExternalReferences(String containerUniqueId,
- String compInstanceUniqueId) {
- GraphVertex serviceVertex = janusGraphDao.getVertexById(containerUniqueId)
- .left()
- .on(operationUtils::onJanusGraphOperationFailure);
-
+ public Map<String, List<String>> getAllExternalReferences(String containerUniqueId, String compInstanceUniqueId) {
+ GraphVertex serviceVertex = janusGraphDao.getVertexById(containerUniqueId).left().on(operationUtils::onJanusGraphOperationFailure);
Either<GraphVertex, JanusGraphOperationStatus> dataVertex = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
if (dataVertex.isRight()) {
return new HashMap<>();
}
GraphVertex externalRefsVertex = dataVertex.left().value();
- Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = externalRefsVertex == null ? null : (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
+ Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData =
+ externalRefsVertex == null ? null : (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
if (externalReferencesFullData != null) {
- return externalReferencesFullData
- .getOrDefault(compInstanceUniqueId, new MapComponentInstanceExternalRefs())
- .getComponentInstanceExternalRefs();
+ return externalReferencesFullData.getOrDefault(compInstanceUniqueId, new MapComponentInstanceExternalRefs())
+ .getComponentInstanceExternalRefs();
}
return emptyMap();
}
@@ -264,28 +237,25 @@ public class ExternalReferencesOperation extends BaseOperation {
public Either<List<String>, ActionStatus> getExternalReferences(String assetUuid, String componentInstanceName, String objectType) {
//Get Service vertex
Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(assetUuid);
- if (vertexById.isRight()){
+ if (vertexById.isRight()) {
return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
}
-
GraphVertex serviceVertex = vertexById.left().value();
final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex);
if (compInstanceUniqueId == null) {
return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
}
-
//Get the external references map vertex
final Either<GraphVertex, JanusGraphOperationStatus> dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
-
//Check whether data vertex found
GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null;
if (externalRefsVertex != null) {
- Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
+ Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex
+ .getJson();
if (externalReferencesFullData != null) {
return Either.left(getExternalReferencesByObjectId(externalReferencesFullData, compInstanceUniqueId, objectType));
}
}
-
//No external References Node found on this asset
return Either.left(new LinkedList());
}
@@ -298,23 +268,27 @@ public class ExternalReferencesOperation extends BaseOperation {
this.idMapper = idMapper;
}
- private List<String> getExternalReferencesByObjectId(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType) {
+ private List<String> getExternalReferencesByObjectId(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData,
+ String componentInstanceId, String objectType) {
MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId);
List<String> externalRefsByObjectType = externalRefsMap.getExternalRefsByObjectType(objectType);
return externalRefsByObjectType != null ? externalRefsByObjectType : new LinkedList<>();
}
- private boolean updateExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType, String oldRef, String newRef) {
+ private boolean updateExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId,
+ String objectType, String oldRef, String newRef) {
MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId);
return externalRefsMap.replaceExternalRef(objectType, oldRef, newRef);
}
- private boolean deleteExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType, String reference) {
+ private boolean deleteExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId,
+ String objectType, String reference) {
MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId);
return externalRefsMap.deleteExternalRef(objectType, reference);
}
- private boolean addExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType, String reference) {
+ private boolean addExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId,
+ String objectType, String reference) {
MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId);
return externalRefsMap.addExternalRef(objectType, reference);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ForwardingPathOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ForwardingPathOperation.java
index f7372a6e28..47ac0a0f71 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ForwardingPathOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ForwardingPathOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
-import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.model.Service;
@@ -34,62 +38,58 @@ import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.*;
-
@org.springframework.stereotype.Component("forwarding-paths-operations")
public class ForwardingPathOperation extends BaseOperation {
- private static final Logger log = Logger.getLogger(ForwardingPathOperation.class.getName());
+ private static final Logger log = Logger.getLogger(ForwardingPathOperation.class.getName());
public Either<Set<String>, StorageOperationStatus> deleteForwardingPath(Service service, Set<String> forwardingPathsToDelete) {
Either<Set<String>, StorageOperationStatus> result = null;
Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex;
StorageOperationStatus status = null;
-
if (result == null) {
- getComponentVertex = janusGraphDao
- .getVertexById(service.getUniqueId(), JsonParseFlagEnum.NoParse);
+ getComponentVertex = janusGraphDao.getVertexById(service.getUniqueId(), JsonParseFlagEnum.NoParse);
if (getComponentVertex.isRight()) {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
}
}
if (result == null) {
-
- status = deleteToscaDataElements(service.getUniqueId(), EdgeLabelEnum.FORWARDING_PATH,new ArrayList<>(forwardingPathsToDelete));
-
+ status = deleteToscaDataElements(service.getUniqueId(), EdgeLabelEnum.FORWARDING_PATH, new ArrayList<>(forwardingPathsToDelete));
if (status != StorageOperationStatus.OK) {
result = Either.right(status);
}
}
-
if (result == null) {
result = Either.left(forwardingPathsToDelete);
}
return result;
}
- public Either<ForwardingPathDataDefinition, StorageOperationStatus> addForwardingPath(String serviceId, ForwardingPathDataDefinition currentPath) {
+ public Either<ForwardingPathDataDefinition, StorageOperationStatus> addForwardingPath(String serviceId,
+ ForwardingPathDataDefinition currentPath) {
return addOrUpdateForwardingPath(false, serviceId, currentPath);
}
- public Either<ForwardingPathDataDefinition, StorageOperationStatus> updateForwardingPath(String serviceId, ForwardingPathDataDefinition currentPath) {
+ public Either<ForwardingPathDataDefinition, StorageOperationStatus> updateForwardingPath(String serviceId,
+ ForwardingPathDataDefinition currentPath) {
return addOrUpdateForwardingPath(true, serviceId, currentPath);
}
- private Either<ForwardingPathDataDefinition, StorageOperationStatus> addOrUpdateForwardingPath(boolean isUpdateAction, String serviceId, ForwardingPathDataDefinition currentPath) {
-
+ private Either<ForwardingPathDataDefinition, StorageOperationStatus> addOrUpdateForwardingPath(boolean isUpdateAction, String serviceId,
+ ForwardingPathDataDefinition currentPath) {
StorageOperationStatus statusRes;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(serviceId, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(log, CommonUtility.LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", serviceId, status);
+ CommonUtility
+ .addRecordToLog(log, CommonUtility.LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ",
+ serviceId, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
return Either.right(statusRes);
}
GraphVertex serviceVertex = getToscaElementRes.left().value();
- if (!isUpdateAction){
+ if (!isUpdateAction) {
currentPath.setUniqueId(UUID.randomUUID().toString());
}
statusRes = performUpdateToscaAction(isUpdateAction, serviceVertex, Arrays.asList(currentPath), JsonPresentationFields.FORWARDING_PATH);
@@ -100,19 +100,16 @@ public class ForwardingPathOperation extends BaseOperation {
}
return Either.left(currentPath);
}
-
}
-
- private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, GraphVertex graphVertex, List<ForwardingPathDataDefinition> toscaDataList, JsonPresentationFields mapKeyField) {
+ private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, GraphVertex graphVertex,
+ List<ForwardingPathDataDefinition> toscaDataList, JsonPresentationFields mapKeyField) {
if (isUpdate) {
- return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList, JsonPresentationFields.UNIQUE_ID);
+ return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList,
+ JsonPresentationFields.UNIQUE_ID);
} else {
- return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList, JsonPresentationFields.UNIQUE_ID);
+ return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList,
+ JsonPresentationFields.UNIQUE_ID);
}
}
-
}
-
-
-
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java
index c2bb1eb62f..8fe4cffac3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java
@@ -17,125 +17,148 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Collectors;
import org.apache.commons.collections.MapUtils;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
-import org.openecomp.sdc.be.datatypes.elements.*;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty;
import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
-import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.Component;
+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.be.model.jsonjanusgraph.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.StorageException;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.utils.GroupUtils;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
@org.springframework.stereotype.Component("groups-operation")
public class GroupsOperation extends BaseOperation {
private static final Logger log = Logger.getLogger(GroupsOperation.class.getName());
- public StorageOperationStatus deleteCalculatedCapabilitiesWithProperties(String componentId, List<GroupDefinition> groupDefinitions) {
- Optional<StorageOperationStatus> error = groupDefinitions.stream().map(g->removeCalculatedCapabilityFromComponent(componentId, g.getUniqueId())).filter(status-> status!=StorageOperationStatus.OK).findFirst();
- if(!error.isPresent()){
- Map<String, MapCapabilityProperty> extractCapabilityPropertiesFromGroups = ModelConverter.extractCapabilityPropertiesFromGroups(groupDefinitions, false);
- error = extractCapabilityPropertiesFromGroups.keySet().stream().map(k->removeCalculatedCapabilityPropertiesFromComponent(componentId, k)).filter(status-> status!=StorageOperationStatus.OK).findFirst();
- }
- if(error.isPresent()){
- return error.get();
- }
- return StorageOperationStatus.OK;
- }
+ public StorageOperationStatus deleteCalculatedCapabilitiesWithProperties(String componentId, List<GroupDefinition> groupDefinitions) {
+ Optional<StorageOperationStatus> error = groupDefinitions.stream()
+ .map(g -> removeCalculatedCapabilityFromComponent(componentId, g.getUniqueId())).filter(status -> status != StorageOperationStatus.OK)
+ .findFirst();
+ if (!error.isPresent()) {
+ Map<String, MapCapabilityProperty> extractCapabilityPropertiesFromGroups = ModelConverter
+ .extractCapabilityPropertiesFromGroups(groupDefinitions, false);
+ error = extractCapabilityPropertiesFromGroups.keySet().stream()
+ .map(k -> removeCalculatedCapabilityPropertiesFromComponent(componentId, k)).filter(status -> status != StorageOperationStatus.OK)
+ .findFirst();
+ }
+ if (error.isPresent()) {
+ return error.get();
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ /**
+ * Adds the map of the calculated capabilities and the map of the calculated capabilities properties the the component on the graph
+ *
+ * @param componentId
+ * @param calculatedCapabilities
+ * @param calculatedCapabilitiesProperties
+ * @return status of the result the operation
+ */
+ public StorageOperationStatus addCalculatedCapabilitiesWithProperties(String componentId,
+ Map<String, MapListCapabilityDataDefinition> calculatedCapabilities,
+ Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) {
+ Optional<StorageOperationStatus> error = calculatedCapabilities.entrySet().stream()
+ .map(e -> addElementToComponent(componentId, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, e))
+ .filter(status -> status != StorageOperationStatus.OK).findFirst();
+ if (!error.isPresent()) {
+ error = calculatedCapabilitiesProperties.entrySet().stream().map(e -> addCalculatedCapabilityPropertiesToComponent(componentId, e))
+ .filter(status -> status != StorageOperationStatus.OK).findFirst();
+ }
+ if (error.isPresent()) {
+ return error.get();
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public StorageOperationStatus updateCalculatedCapabilitiesWithProperties(String componentId,
+ Map<String, MapListCapabilityDataDefinition> calculatedCapabilities,
+ Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) {
+ Optional<StorageOperationStatus> error = calculatedCapabilities.entrySet().stream()
+ .map(e -> updateCalculatedCapabilityOfComponent(componentId, e)).filter(status -> status != StorageOperationStatus.OK).findFirst();
+ if (!error.isPresent()) {
+ error = calculatedCapabilitiesProperties.entrySet().stream().map(e -> updateCalculatedCapabilityPropertiesOnComponent(componentId, e))
+ .filter(status -> status != StorageOperationStatus.OK).findFirst();
+ }
+ if (error.isPresent()) {
+ return error.get();
+ }
+ return StorageOperationStatus.OK;
+ }
- /**
- * Adds the map of the calculated capabilities and the map of the calculated capabilities properties the the component on the graph
- * @param componentId
- * @param calculatedCapabilities
- * @param calculatedCapabilitiesProperties
- * @return status of the result the operation
- */
- public StorageOperationStatus addCalculatedCapabilitiesWithProperties(String componentId, Map<String, MapListCapabilityDataDefinition> calculatedCapabilities, Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) {
+ private StorageOperationStatus updateCalculatedCapabilityOfComponent(String componentId,
+ Entry<String, MapListCapabilityDataDefinition> capabilities) {
+ if (MapUtils.isNotEmpty(capabilities.getValue().getMapToscaDataDefinition())) {
+ return updateToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAPABILITIES, capabilities.getValue(),
+ capabilities.getKey());
+ }
+ return StorageOperationStatus.OK;
+ }
- Optional<StorageOperationStatus> error = calculatedCapabilities.entrySet().stream().map(e-> addElementToComponent(componentId, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst();
- if(!error.isPresent()){
- error = calculatedCapabilitiesProperties.entrySet().stream().map(e->addCalculatedCapabilityPropertiesToComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst();
- }
- if(error.isPresent()){
- return error.get();
- }
- return StorageOperationStatus.OK;
- }
-
- public StorageOperationStatus updateCalculatedCapabilitiesWithProperties(String componentId, Map<String, MapListCapabilityDataDefinition> calculatedCapabilities, Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) {
+ private StorageOperationStatus addCalculatedCapabilityPropertiesToComponent(String componentId, Entry<String, MapCapabilityProperty> properties) {
+ if (MapUtils.isNotEmpty(properties.getValue().getMapToscaDataDefinition())) {
+ return addToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
+ VertexTypeEnum.CALCULATED_CAP_PROPERTIES, properties.getValue(), properties.getKey());
+ }
+ return StorageOperationStatus.OK;
+ }
- Optional<StorageOperationStatus> error = calculatedCapabilities.entrySet().stream().map(e->updateCalculatedCapabilityOfComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst();
- if(!error.isPresent()){
- error = calculatedCapabilitiesProperties.entrySet().stream().map(e->updateCalculatedCapabilityPropertiesOnComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst();
- }
- if(error.isPresent()){
- return error.get();
- }
- return StorageOperationStatus.OK;
- }
+ private StorageOperationStatus updateCalculatedCapabilityPropertiesOnComponent(String componentId,
+ Entry<String, MapCapabilityProperty> properties) {
+ if (MapUtils.isNotEmpty(properties.getValue().getMapToscaDataDefinition())) {
+ return updateToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, properties.getValue(),
+ properties.getKey());
+ }
+ return StorageOperationStatus.OK;
+ }
- private StorageOperationStatus updateCalculatedCapabilityOfComponent(String componentId, Entry<String, MapListCapabilityDataDefinition> capabilities){
- if(MapUtils.isNotEmpty(capabilities.getValue().getMapToscaDataDefinition()))
- return updateToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAPABILITIES, capabilities.getValue(), capabilities.getKey());
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus addCalculatedCapabilityPropertiesToComponent(String componentId, Entry<String, MapCapabilityProperty> properties){
- if(MapUtils.isNotEmpty(properties.getValue().getMapToscaDataDefinition()))
- return addToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, properties.getValue(), properties.getKey());
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus updateCalculatedCapabilityPropertiesOnComponent(String componentId, Entry<String, MapCapabilityProperty> properties){
- if(MapUtils.isNotEmpty(properties.getValue().getMapToscaDataDefinition()))
- return updateToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, properties.getValue(), properties.getKey());
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus removeCalculatedCapabilityFromComponent(String componentId, String groupId){
- return deleteToscaDataDeepElementsBlockOfToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, groupId);
- }
-
- private StorageOperationStatus removeCalculatedCapabilityPropertiesFromComponent(String componentId, String groupId){
- return deleteToscaDataDeepElementsBlockOfToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, groupId);
- }
+ private StorageOperationStatus removeCalculatedCapabilityFromComponent(String componentId, String groupId) {
+ return deleteToscaDataDeepElementsBlockOfToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAPABILITIES,
+ VertexTypeEnum.CALCULATED_CAPABILITIES, groupId);
+ }
+ private StorageOperationStatus removeCalculatedCapabilityPropertiesFromComponent(String componentId, String groupId) {
+ return deleteToscaDataDeepElementsBlockOfToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
+ VertexTypeEnum.CALCULATED_CAP_PROPERTIES, groupId);
+ }
public Either<List<GroupDefinition>, StorageOperationStatus> createGroups(Component component, Map<String, GroupDataDefinition> groups) {
-
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex = null;
StorageOperationStatus status = null;
-
- getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
- if (getComponentVertex.isRight()) {
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
- }
+ getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (getComponentVertex.isRight()) {
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
+ }
if (result == null) {
status = topologyTemplateOperation.associateGroupsToComponent(getComponentVertex.left().value(), groups);
if (status != StorageOperationStatus.OK) {
@@ -152,21 +175,19 @@ public class GroupsOperation extends BaseOperation {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex;
StorageOperationStatus status;
-
- getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
- if (getComponentVertex.isRight()) {
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
- }
+ getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (getComponentVertex.isRight()) {
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
+ }
if (result == null) {
- status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.CI_INVARIANT_NAME);
-
+ status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups,
+ JsonPresentationFields.CI_INVARIANT_NAME);
if (status != StorageOperationStatus.OK) {
result = Either.right(status);
}
}
-
if (result == null) {
- Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap(GroupDataDefinition::getInvariantName, x->x));
+ Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap(GroupDataDefinition::getInvariantName, x -> x));
result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup));
}
return result;
@@ -176,52 +197,48 @@ public class GroupsOperation extends BaseOperation {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex = null;
StorageOperationStatus status = null;
-
- getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
- if (getComponentVertex.isRight()) {
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
- }
+ getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (getComponentVertex.isRight()) {
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
+ }
if (result == null) {
- List<String> groupInvariantName = groups.stream().map(GroupDataDefinition::getInvariantName).collect(Collectors.toList());
+ List<String> groupInvariantName = groups.stream().map(GroupDataDefinition::getInvariantName).collect(Collectors.toList());
status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, groupInvariantName);
-
if (status != StorageOperationStatus.OK) {
result = Either.right(status);
}
}
-
if (result == null) {
- Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( GroupDataDefinition::getName, x->x));
+ Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap(GroupDataDefinition::getName, x -> x));
result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup));
}
return result;
}
- public <T extends GroupDataDefinition> Either<List<GroupDefinition>, StorageOperationStatus> updateGroups(Component component, List<T> groups, PromoteVersionEnum promoteVersion) {
+ public <T extends GroupDataDefinition> Either<List<GroupDefinition>, StorageOperationStatus> updateGroups(Component component, List<T> groups,
+ PromoteVersionEnum promoteVersion) {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex = null;
StorageOperationStatus status = null;
-
- getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
- if (getComponentVertex.isRight()) {
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
- }
+ getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (getComponentVertex.isRight()) {
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
+ }
if (result == null) {
groups.forEach(gr -> {
updateVersion(promoteVersion, gr);
- // String groupUUID = UniqueIdBuilder.generateUUID();
- // gr.setGroupUUID(groupUUID);
- });
-
- status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.CI_INVARIANT_NAME);
+ // String groupUUID = UniqueIdBuilder.generateUUID();
+ // gr.setGroupUUID(groupUUID);
+ });
+ status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups,
+ JsonPresentationFields.CI_INVARIANT_NAME);
if (status != StorageOperationStatus.OK) {
result = Either.right(status);
}
}
-
if (result == null) {
- Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( GroupDataDefinition::getInvariantName, x->x));
+ Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap(GroupDataDefinition::getInvariantName, x -> x));
result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup));
updateGroupsOnComponent(component, ModelConverter.convertToGroupDefinitions(mapGroup));
}
@@ -231,10 +248,8 @@ public class GroupsOperation extends BaseOperation {
private void updateGroupsOnComponent(Component component, List<GroupDefinition> groupsToUpdate) {
List<GroupDefinition> groupsFromResource = component.getGroups();
for (GroupDefinition group : groupsToUpdate) {
- Optional<GroupDefinition> op = groupsFromResource.stream()
- .filter(p -> p.getInvariantName()
- .equalsIgnoreCase(group.getInvariantName()))
- .findAny();
+ Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
+ .findAny();
if (op.isPresent()) {
GroupDefinition groupToUpdate = op.get();
groupToUpdate.setMembers(group.getMembers());
@@ -245,68 +260,51 @@ public class GroupsOperation extends BaseOperation {
}
private <T extends GroupDataDefinition> void updateVersion(PromoteVersionEnum promoteVersion, T group) {
-
group.setVersion(GroupUtils.updateVersion(promoteVersion, group.getVersion()));
}
public void updateGroupOnComponent(String componentId, GroupDefinition groupDefinition, PromoteVersionEnum promoteMinorVersion) {
- GraphVertex componentVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
- .left()
- .on(this::onJanusGraphError);
- updateVersion(promoteMinorVersion, groupDefinition);
-
- StorageOperationStatus updateToscaResult = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition,
- JsonPresentationFields.CI_INVARIANT_NAME);
-
+ GraphVertex componentVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata).left().on(this::onJanusGraphError);
+ updateVersion(promoteMinorVersion, groupDefinition);
+ StorageOperationStatus updateToscaResult = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS,
+ groupDefinition, JsonPresentationFields.CI_INVARIANT_NAME);
if (StorageOperationStatus.OK != updateToscaResult) {
throw new StorageException(updateToscaResult, groupDefinition.getUniqueId());
}
-
updateLastUpdateDate(componentVertex);
}
-
public <T extends GroupDataDefinition> StorageOperationStatus updateGroupsOnComponent(String componentId, List<T> groups) {
- GraphVertex componentVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
- .left()
- .on(this::onJanusGraphError);
-
- StorageOperationStatus updateToscaResult = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.CI_INVARIANT_NAME);
-
-
+ GraphVertex componentVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata).left().on(this::onJanusGraphError);
+ StorageOperationStatus updateToscaResult = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups,
+ JsonPresentationFields.CI_INVARIANT_NAME);
if (StorageOperationStatus.OK != updateToscaResult) {
throw new StorageException(updateToscaResult);
}
-
updateLastUpdateDate(componentVertex);
-
return updateToscaResult;
-
}
private void updateLastUpdateDate(GraphVertex componentVertex) {
componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
- janusGraphDao.updateVertex(componentVertex)
- .left()
- .on(this::onJanusGraphError);
+ janusGraphDao.updateVertex(componentVertex).left().on(this::onJanusGraphError);
}
GraphVertex onJanusGraphError(JanusGraphOperationStatus janusGraphOperationStatus) {
- throw new StorageException(
- DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
+ throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
}
- public Either<List<GroupProperty>, StorageOperationStatus> updateGroupPropertiesOnComponent(String componentId, GroupDefinition group, List<GroupProperty> newGroupProperties, PromoteVersionEnum promoteMinorVersion) {
-
+ public Either<List<GroupProperty>, StorageOperationStatus> updateGroupPropertiesOnComponent(String componentId, GroupDefinition group,
+ List<GroupProperty> newGroupProperties,
+ PromoteVersionEnum promoteMinorVersion) {
Either<List<GroupProperty>, StorageOperationStatus> result = null;
Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex = null;
GraphVertex componentVertex = null;
-
- getComponentVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
- if (getComponentVertex.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId);
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
- }
+ getComponentVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
+ if (getComponentVertex.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId);
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
+ }
if (result == null) {
componentVertex = getComponentVertex.left().value();
//update
@@ -318,7 +316,8 @@ public class GroupsOperation extends BaseOperation {
}
});
updateVersion(promoteMinorVersion, group);
- StorageOperationStatus updateDataRes = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, group, JsonPresentationFields.CI_INVARIANT_NAME);
+ StorageOperationStatus updateDataRes = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, group,
+ JsonPresentationFields.CI_INVARIANT_NAME);
if (updateDataRes != StorageOperationStatus.OK) {
log.debug("Failed to update properties for group {} error {}", group.getName(), updateDataRes);
result = Either.right(updateDataRes);
@@ -328,7 +327,8 @@ public class GroupsOperation extends BaseOperation {
componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
Either<GraphVertex, JanusGraphOperationStatus> updateRes = janusGraphDao.updateVertex(componentVertex);
if (updateRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the component {}. Status is {} ", componentId, updateRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the component {}. Status is {} ", componentId,
+ updateRes.right().value());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateRes.right().value()));
}
}
@@ -338,13 +338,10 @@ public class GroupsOperation extends BaseOperation {
return result;
}
-
-
- public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstances(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) {
-
+ public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstances(Component component, String instanceId,
+ List<GroupInstance> updatedGroupInstances) {
Either<List<GroupInstance>, StorageOperationStatus> result = null;
StorageOperationStatus status = null;
-
Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex = janusGraphDao
.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
if (getComponentVertex.isRight()) {
@@ -353,7 +350,8 @@ public class GroupsOperation extends BaseOperation {
if (result == null) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(instanceId);
- status = updateToscaDataDeepElementsOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, updatedGroupInstances, pathKeys, JsonPresentationFields.NAME);
+ status = updateToscaDataDeepElementsOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS,
+ updatedGroupInstances, pathKeys, JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
result = Either.right(status);
}
@@ -365,41 +363,49 @@ public class GroupsOperation extends BaseOperation {
}
public Either<GroupDefinition, StorageOperationStatus> updateGroup(Component component, GroupDefinition currentGroup) {
- StorageOperationStatus status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.CI_INVARIANT_NAME);
+ StorageOperationStatus status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS,
+ currentGroup, JsonPresentationFields.CI_INVARIANT_NAME);
if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(),
+ component.getName(), status);
return Either.right(status);
}
return Either.left(currentGroup);
}
public StorageOperationStatus deleteGroup(Component component, String currentGroupName) {
- StorageOperationStatus status = deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroupName, JsonPresentationFields.CI_INVARIANT_NAME);
+ StorageOperationStatus status = deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroupName,
+ JsonPresentationFields.CI_INVARIANT_NAME);
if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName, component.getName(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName,
+ component.getName(), status);
}
return status;
}
- public Either<GroupDefinition, StorageOperationStatus> addGroup(Component component, GroupDefinition currentGroup, PromoteVersionEnum promoteMinorVersion) {
+ public Either<GroupDefinition, StorageOperationStatus> addGroup(Component component, GroupDefinition currentGroup,
+ PromoteVersionEnum promoteMinorVersion) {
updateVersion(promoteMinorVersion, currentGroup);
- StorageOperationStatus status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.CI_INVARIANT_NAME);
+ StorageOperationStatus status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup,
+ JsonPresentationFields.CI_INVARIANT_NAME);
if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(),
+ component.getName(), status);
return Either.right(status);
}
return Either.left(currentGroup);
}
- public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValuesOnGraph(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
+ public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValuesOnGraph(String componentId, String instanceId,
+ GroupInstance oldGroupInstance,
+ List<GroupInstanceProperty> newProperties) {
+ Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
if (getComponentVertex.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
}
-
List<PropertyDataDefinition> propertiesOld = oldGroupInstance.getProperties();
newProperties.forEach(np -> {
Optional<PropertyDataDefinition> prop = propertiesOld.stream().filter(p -> p.getName().equals(np.getName())).findFirst();
@@ -412,7 +418,8 @@ public class GroupsOperation extends BaseOperation {
groupInstanceDataDefinition.setModificationTime(System.currentTimeMillis());
groupInstanceDataDefinition.setCustomizationUUID(UUID.randomUUID().toString());
pathKeys.add(instanceId);
- StorageOperationStatus updateDataRes = updateToscaDataDeepElementOfToscaElement(componentId, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, groupInstanceDataDefinition, pathKeys, JsonPresentationFields.NAME);
+ StorageOperationStatus updateDataRes = updateToscaDataDeepElementOfToscaElement(componentId, EdgeLabelEnum.INST_GROUPS,
+ VertexTypeEnum.INST_GROUPS, groupInstanceDataDefinition, pathKeys, JsonPresentationFields.NAME);
if (updateDataRes != StorageOperationStatus.OK) {
log.debug("Failed to update properties for group instance {} error {}", oldGroupInstance.getName(), updateDataRes);
return Either.right(updateDataRes);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InstancesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InstancesOperation.java
index 3378e03318..af573a2412 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InstancesOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InstancesOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.jsonjanusgraph.operations;
public class InstancesOperation extends BaseOperation {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperation.java
index e2cc09fc30..bc67281035 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/InterfaceOperation.java
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import fj.data.Either;
@@ -36,54 +35,47 @@ import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
public class InterfaceOperation extends BaseOperation {
public Either<List<InterfaceDefinition>, StorageOperationStatus> addInterfaces(String componentId,
- List<InterfaceDefinition> interfaceDefinitions) {
+ List<InterfaceDefinition> interfaceDefinitions) {
return addOrUpdateInterfaces(false, componentId, interfaceDefinitions);
}
- private Either<List<InterfaceDefinition>, StorageOperationStatus> addOrUpdateInterfaces(boolean isUpdateAction,
- String componentId, List<InterfaceDefinition> interfaceDefinitions) {
-
- List<ToscaDataDefinition> interfaceDataDefinitions =
- interfaceDefinitions.stream().map(InterfaceDataDefinition::new).collect(Collectors.toList());
- StorageOperationStatus statusRes =
- performUpdateToscaAction(isUpdateAction, componentId, interfaceDataDefinitions, EdgeLabelEnum.INTERFACE,
- VertexTypeEnum.INTERFACE);
+ private Either<List<InterfaceDefinition>, StorageOperationStatus> addOrUpdateInterfaces(boolean isUpdateAction, String componentId,
+ List<InterfaceDefinition> interfaceDefinitions) {
+ List<ToscaDataDefinition> interfaceDataDefinitions = interfaceDefinitions.stream().map(InterfaceDataDefinition::new)
+ .collect(Collectors.toList());
+ StorageOperationStatus statusRes = performUpdateToscaAction(isUpdateAction, componentId, interfaceDataDefinitions, EdgeLabelEnum.INTERFACE,
+ VertexTypeEnum.INTERFACE);
if (!statusRes.equals(StorageOperationStatus.OK)) {
return Either.right(statusRes);
}
return Either.left(interfaceDefinitions);
}
- private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, String componentId,
- List<ToscaDataDefinition> toscaDataList, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) {
+ private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, String componentId, List<ToscaDataDefinition> toscaDataList,
+ EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) {
if (isUpdate) {
- return updateToscaDataOfToscaElement(componentId, edgeLabel, vertexLabel, toscaDataList,
- JsonPresentationFields.UNIQUE_ID);
+ return updateToscaDataOfToscaElement(componentId, edgeLabel, vertexLabel, toscaDataList, JsonPresentationFields.UNIQUE_ID);
} else {
- return addToscaDataToToscaElement(componentId, edgeLabel, vertexLabel, toscaDataList,
- JsonPresentationFields.UNIQUE_ID);
+ return addToscaDataToToscaElement(componentId, edgeLabel, vertexLabel, toscaDataList, JsonPresentationFields.UNIQUE_ID);
}
}
public Either<List<InterfaceDefinition>, StorageOperationStatus> updateInterfaces(String componentId,
- List<InterfaceDefinition> interfaceDefinitions) {
+ List<InterfaceDefinition> interfaceDefinitions) {
return addOrUpdateInterfaces(true, componentId, interfaceDefinitions);
}
public Either<String, StorageOperationStatus> deleteInterface(String componentId, String interfacesToDelete) {
-
StorageOperationStatus statusRes = deleteToscaDataElements(componentId, EdgeLabelEnum.INTERFACE,
- Collections.singletonList(interfacesToDelete));
+ Collections.singletonList(interfacesToDelete));
if (!statusRes.equals(StorageOperationStatus.OK)) {
return Either.right(statusRes);
}
-
- Either<Map<String, InterfaceDataDefinition>, JanusGraphOperationStatus> componentEither =
- getDataFromGraph(componentId, EdgeLabelEnum.INTERFACE);
+ Either<Map<String, InterfaceDataDefinition>, JanusGraphOperationStatus> componentEither = getDataFromGraph(componentId,
+ EdgeLabelEnum.INTERFACE);
if (componentEither.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(componentEither.right().value()));
}
-
Map<String, InterfaceDataDefinition> interfaceDataDefinitionMap = componentEither.left().value();
if (MapUtils.isEmpty(interfaceDataDefinitionMap)) {
statusRes = removeToscaData(componentId, EdgeLabelEnum.INTERFACE, VertexTypeEnum.INTERFACE);
@@ -91,8 +83,6 @@ public class InterfaceOperation extends BaseOperation {
return Either.right(statusRes);
}
}
-
return Either.left(interfacesToDelete);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeFilterOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeFilterOperation.java
index 050709d6d5..c99ff9cd43 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeFilterOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeFilterOperation.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import com.google.common.collect.ImmutableList;
@@ -48,75 +47,59 @@ public class NodeFilterOperation extends BaseOperation {
private static Logger logger = Logger.getLogger(NodeFilterOperation.class);
- public Either<Set<String>, StorageOperationStatus> deleteNodeFilters(final Component component,
- final Set<String> componentInstanceIds) {
+ public Either<Set<String>, StorageOperationStatus> deleteNodeFilters(final Component component, final Set<String> componentInstanceIds) {
final Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex;
final Either<GraphVertex, JanusGraphOperationStatus> getNodeFilterVertex;
StorageOperationStatus status;
-
getComponentVertex = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
if (getComponentVertex.isRight()) {
- return Either.right(
- DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value()));
}
- getNodeFilterVertex = janusGraphDao.getChildVertex(getComponentVertex.left().value(),
- EdgeLabelEnum.NODE_FILTER_TEMPLATE, JsonParseFlagEnum.NoParse);
+ getNodeFilterVertex = janusGraphDao
+ .getChildVertex(getComponentVertex.left().value(), EdgeLabelEnum.NODE_FILTER_TEMPLATE, JsonParseFlagEnum.NoParse);
if (getNodeFilterVertex.isLeft()) {
- status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.NODE_FILTER_TEMPLATE,
- new ArrayList<>(componentInstanceIds));
+ status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.NODE_FILTER_TEMPLATE, new ArrayList<>(componentInstanceIds));
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
}
-
return Either.left(componentInstanceIds);
}
-
- public Either<String, StorageOperationStatus> deleteNodeFilter(final Component component,
- final String componentInstanceId) {
- final Either<Set<String>, StorageOperationStatus> listStorageOperationStatusEither =
- deleteNodeFilters(component, ImmutableSet.of(componentInstanceId));
+ public Either<String, StorageOperationStatus> deleteNodeFilter(final Component component, final String componentInstanceId) {
+ final Either<Set<String>, StorageOperationStatus> listStorageOperationStatusEither = deleteNodeFilters(component,
+ ImmutableSet.of(componentInstanceId));
if (listStorageOperationStatusEither.isRight()) {
return Either.right(listStorageOperationStatusEither.right().value());
}
return Either.left(componentInstanceId);
}
-
- public Either<CINodeFilterDataDefinition, StorageOperationStatus> createNodeFilter(final String componentId,
- final String componentInstanceId) {
+ public Either<CINodeFilterDataDefinition, StorageOperationStatus> createNodeFilter(final String componentId, final String componentInstanceId) {
CINodeFilterDataDefinition nodeFilterDataDefinition = new CINodeFilterDataDefinition();
return addOrUpdateNodeFilter(false, componentId, componentInstanceId, nodeFilterDataDefinition);
}
- public Either<CINodeFilterDataDefinition, StorageOperationStatus> deleteConstraint(final String serviceId,
- final String componentInstanceId,
+ public Either<CINodeFilterDataDefinition, StorageOperationStatus> deleteConstraint(final String serviceId, final String componentInstanceId,
final CINodeFilterDataDefinition nodeFilterDataDefinition,
final int propertyIndex,
final NodeFilterConstraintType nodeFilterConstraintType) {
-
if (NodeFilterConstraintType.PROPERTIES.equals(nodeFilterConstraintType)) {
- final ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> properties =
- nodeFilterDataDefinition.getProperties();
+ final ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> properties = nodeFilterDataDefinition.getProperties();
properties.getListToscaDataDefinition().remove(propertyIndex);
nodeFilterDataDefinition.setProperties(properties);
} else if (NodeFilterConstraintType.CAPABILITIES.equals(nodeFilterConstraintType)) {
- final ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> capabilities =
- nodeFilterDataDefinition.getCapabilities();
+ final ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> capabilities = nodeFilterDataDefinition.getCapabilities();
capabilities.getListToscaDataDefinition().remove(propertyIndex);
nodeFilterDataDefinition.setCapabilities(capabilities);
}
return addOrUpdateNodeFilter(true, serviceId, componentInstanceId, nodeFilterDataDefinition);
}
- public Either<CINodeFilterDataDefinition, StorageOperationStatus> addNewProperty(
- final String componentId, final String componentInstanceId,
- final CINodeFilterDataDefinition nodeFilterDataDefinition,
- final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition) {
-
- ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> properties =
- nodeFilterDataDefinition.getProperties();
+ public Either<CINodeFilterDataDefinition, StorageOperationStatus> addNewProperty(final String componentId, final String componentInstanceId,
+ final CINodeFilterDataDefinition nodeFilterDataDefinition,
+ final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition) {
+ ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> properties = nodeFilterDataDefinition.getProperties();
if (properties == null) {
properties = new ListDataDefinition<>();
nodeFilterDataDefinition.setProperties(properties);
@@ -126,14 +109,11 @@ public class NodeFilterOperation extends BaseOperation {
return addOrUpdateNodeFilter(true, componentId, componentInstanceId, nodeFilterDataDefinition);
}
- public Either<CINodeFilterDataDefinition, StorageOperationStatus> addNewCapabilities(
- final String componentId, final String componentInstanceId,
- final CINodeFilterDataDefinition nodeFilterDataDefinition,
- final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition) {
-
- ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> capabilities =
- nodeFilterDataDefinition.getCapabilities();
- if(capabilities == null) {
+ public Either<CINodeFilterDataDefinition, StorageOperationStatus> addNewCapabilities(final String componentId, final String componentInstanceId,
+ final CINodeFilterDataDefinition nodeFilterDataDefinition,
+ final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition) {
+ ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> capabilities = nodeFilterDataDefinition.getCapabilities();
+ if (capabilities == null) {
capabilities = new ListDataDefinition<>();
nodeFilterDataDefinition.setCapabilities(capabilities);
}
@@ -142,50 +122,42 @@ public class NodeFilterOperation extends BaseOperation {
return addOrUpdateNodeFilter(true, componentId, componentInstanceId, nodeFilterDataDefinition);
}
- public Either<CINodeFilterDataDefinition, StorageOperationStatus> updateProperties(
- final String componentId, final String componentInstanceId,
- final CINodeFilterDataDefinition nodeFilterDataDefinition,
- final List<RequirementNodeFilterPropertyDataDefinition> requirementNodeFilterPropertyDataDefinition) {
-
- final ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> properties =
- nodeFilterDataDefinition.getProperties();
+ public Either<CINodeFilterDataDefinition, StorageOperationStatus> updateProperties(final String componentId, final String componentInstanceId,
+ final CINodeFilterDataDefinition nodeFilterDataDefinition,
+ final List<RequirementNodeFilterPropertyDataDefinition> requirementNodeFilterPropertyDataDefinition) {
+ final ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> properties = nodeFilterDataDefinition.getProperties();
properties.getListToscaDataDefinition().clear();
properties.getListToscaDataDefinition().addAll(requirementNodeFilterPropertyDataDefinition);
nodeFilterDataDefinition.setProperties(properties);
return addOrUpdateNodeFilter(true, componentId, componentInstanceId, nodeFilterDataDefinition);
}
- public Either<CINodeFilterDataDefinition, StorageOperationStatus> updateCapabilities(
- final String componentId, final String componentInstanceId,
- final CINodeFilterDataDefinition nodeFilterDataDefinition,
- final List<RequirementNodeFilterCapabilityDataDefinition> requirementNodeFilterCapabilityDataDefinitions) {
-
- final ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> capabilities =
- nodeFilterDataDefinition.getCapabilities();
+ public Either<CINodeFilterDataDefinition, StorageOperationStatus> updateCapabilities(final String componentId, final String componentInstanceId,
+ final CINodeFilterDataDefinition nodeFilterDataDefinition,
+ final List<RequirementNodeFilterCapabilityDataDefinition> requirementNodeFilterCapabilityDataDefinitions) {
+ final ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> capabilities = nodeFilterDataDefinition.getCapabilities();
capabilities.getListToscaDataDefinition().clear();
capabilities.getListToscaDataDefinition().addAll(requirementNodeFilterCapabilityDataDefinitions);
nodeFilterDataDefinition.setCapabilities(capabilities);
return addOrUpdateNodeFilter(true, componentId, componentInstanceId, nodeFilterDataDefinition);
}
- public Either<CINodeFilterDataDefinition, StorageOperationStatus> updateNodeFilter(final String serviceId,
- final String componentInstanceId,
+ public Either<CINodeFilterDataDefinition, StorageOperationStatus> updateNodeFilter(final String serviceId, final String componentInstanceId,
final CINodeFilterDataDefinition ciNodeFilterDataDefinition) {
return addOrUpdateNodeFilter(true, serviceId, componentInstanceId, ciNodeFilterDataDefinition);
}
- private Either<CINodeFilterDataDefinition, StorageOperationStatus> addOrUpdateNodeFilter(
- final boolean isUpdateAction, final String componentId, final String componentInstanceId,
- final CINodeFilterDataDefinition ciNodeFilterDataDefinition) {
-
+ private Either<CINodeFilterDataDefinition, StorageOperationStatus> addOrUpdateNodeFilter(final boolean isUpdateAction, final String componentId,
+ final String componentInstanceId,
+ final CINodeFilterDataDefinition ciNodeFilterDataDefinition) {
StorageOperationStatus statusRes;
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes;
-
getToscaElementRes = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
JanusGraphOperationStatus status = getToscaElementRes.right().value();
- CommonUtility.addRecordToLog(logger, CommonUtility.LogLevelEnum.DEBUG,
- "Failed to get tosca element {} upon adding the properties. Status is {}. ", componentId, status);
+ CommonUtility
+ .addRecordToLog(logger, CommonUtility.LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ",
+ componentId, status);
statusRes = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
return Either.right(statusRes);
}
@@ -194,27 +166,22 @@ public class NodeFilterOperation extends BaseOperation {
statusRes = performUpdateToscaAction(isUpdateAction, serviceVertex, ImmutableList.of(ciNodeFilterDataDefinition));
if (!statusRes.equals(StorageOperationStatus.OK)) {
janusGraphDao.rollback();
- logger.error(
- " Failed to perform tosca update for node filter in service {} , component instance {}. status is {}",
- componentId, componentInstanceId, statusRes);
+ logger.error(" Failed to perform tosca update for node filter in service {} , component instance {}. status is {}", componentId,
+ componentInstanceId, statusRes);
return Either.right(statusRes);
}
janusGraphDao.commit();
return Either.left(ciNodeFilterDataDefinition);
}
- private StorageOperationStatus performUpdateToscaAction(final boolean isUpdate,
- final GraphVertex graphVertex,
+ private StorageOperationStatus performUpdateToscaAction(final boolean isUpdate, final GraphVertex graphVertex,
final List<CINodeFilterDataDefinition> toscaDataList) {
if (isUpdate) {
- return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.NODE_FILTER_TEMPLATE,
- VertexTypeEnum.NODE_FILTER_TEMPLATE, toscaDataList, JsonPresentationFields.UNIQUE_ID);
+ return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.NODE_FILTER_TEMPLATE, VertexTypeEnum.NODE_FILTER_TEMPLATE, toscaDataList,
+ JsonPresentationFields.UNIQUE_ID);
} else {
- return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.NODE_FILTER_TEMPLATE,
- VertexTypeEnum.NODE_FILTER_TEMPLATE, toscaDataList, JsonPresentationFields.UNIQUE_ID);
+ return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.NODE_FILTER_TEMPLATE, VertexTypeEnum.NODE_FILTER_TEMPLATE, toscaDataList,
+ JsonPresentationFields.UNIQUE_ID);
}
}
}
-
-
-
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java
index babe44234e..f9e9a46698 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import fj.data.Either;
@@ -125,19 +124,20 @@ import org.openecomp.sdc.common.util.ValidationUtils;
@org.springframework.stereotype.Component("node-template-operation")
public class NodeTemplateOperation extends BaseOperation {
+
+ public static final Integer NON_HEAT_TIMEOUT = 0;
+ static final String HEAT_ENV_NAME = "heatEnv";
+ static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
+ static final String HEAT_ENV_SUFFIX = "env";
private static final String FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR = "Failed to fetch container vertex {} error {}";
private static final String FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE = "Failed to update topology template {} with new component instance {}. ";
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";
- static final String HEAT_ENV_NAME = "heatEnv";
- static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
- static final String HEAT_ENV_SUFFIX = "env";
+ private static final Logger log = Logger.getLogger(NodeTemplateOperation.class.getName());
+ private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(NodeTemplateOperation.class.getName());
private static Integer defaultHeatTimeout;
- public static final Integer NON_HEAT_TIMEOUT = 0;
- private static final Logger log = Logger.getLogger(NodeTemplateOperation.class.getName());
- private static final LoggerSupportability loggerSupportability=LoggerSupportability.getLogger(NodeTemplateOperation.class.getName());
public NodeTemplateOperation() {
defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout().getDefaultMinutes();
if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
@@ -149,15 +149,23 @@ public class NodeTemplateOperation extends BaseOperation {
return defaultHeatTimeout;
}
- Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, String instanceNumberSuffix, ComponentInstance componentInstance,
- boolean allowDeleted, User user) {
+ public static String createCapPropertyKey(String key, String instanceId) {
+ StringBuffer sb = new StringBuffer(instanceId);
+ sb.append(ModelConverter.CAP_PROP_DELIM).append(instanceId).append(ModelConverter.CAP_PROP_DELIM).append(key);
+ return sb.toString();
+ }
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container,
+ ToscaElement originToscaElement,
+ String instanceNumberSuffix,
+ ComponentInstance componentInstance,
+ boolean allowDeleted, User user) {
Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null;
Either<TopologyTemplate, StorageOperationStatus> addComponentInstanceRes = null;
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to create component instance {} in component {}", componentInstance, container.getUniqueId());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to create component instance {} in component {}", componentInstance,
+ container.getUniqueId());
ComponentInstanceDataDefinition componentInstanceData = null;
Either<String, StorageOperationStatus> newInstanceNameRes = null;
-
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseJson);
if (metadataVertex.isRight()) {
@@ -167,19 +175,17 @@ public class NodeTemplateOperation extends BaseOperation {
}
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
if (result == null) {
-
newInstanceNameRes = buildValidateInstanceName(container, originToscaElement, componentInstance, instanceNumberSuffix);
if (newInstanceNameRes.isRight()) {
result = Either.right(newInstanceNameRes.right().value());
}
}
if (result == null) {
- componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), newInstanceNameRes.left().value(), true, originToscaElement);
-
- addComponentInstanceRes = addComponentInstanceToTopologyTemplate(container, originToscaElement, componentInstanceData, metadataVertex.left().value(), allowDeleted, user);
-
+ componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(),
+ newInstanceNameRes.left().value(), true, originToscaElement);
+ addComponentInstanceRes = addComponentInstanceToTopologyTemplate(container, originToscaElement, componentInstanceData,
+ metadataVertex.left().value(), allowDeleted, user);
if (addComponentInstanceRes.isRight()) {
StorageOperationStatus status = addComponentInstanceRes.right().value();
if (status == StorageOperationStatus.NOT_FOUND) {
@@ -191,26 +197,23 @@ public class NodeTemplateOperation extends BaseOperation {
if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy
|| componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) {
result = addCapAndReqToProxyServiceInstance(updatedContainer, componentInstance, componentInstanceData);
- if(result.isRight()) {
+ if (result.isRight()) {
return result;
}
-
result = addServiceInstancePropertiesToProxyServiceInstance(updatedContainer, componentInstance);
- if(result.isRight()) {
- return result;
+ if (result.isRight()) {
+ return result;
}
-
result = addServiceInstanceInputsToProxyServiceInstance(updatedContainer, componentInstance);
- if(result.isRight()) {
+ if (result.isRight()) {
return result;
}
}
if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy
- || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution
- || componentInstance.getOriginType() == OriginTypeEnum.VF
+ || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution || componentInstance.getOriginType() == OriginTypeEnum.VF
|| componentInstance.getOriginType() == OriginTypeEnum.VFC) {
result = addComponentInstanceInterfacesToTopologyTemplate(updatedContainer, componentInstance);
- if(result.isRight()) {
+ if (result.isRight()) {
return result;
}
}
@@ -221,34 +224,38 @@ public class NodeTemplateOperation extends BaseOperation {
return result;
}
- private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addCapAndReqToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance,
- ComponentInstanceDataDefinition componentInstanceData) {
+ private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addCapAndReqToProxyServiceInstance(
+ TopologyTemplate updatedContainer, ComponentInstance componentInstance, ComponentInstanceDataDefinition componentInstanceData) {
Map<String, MapListCapabilityDataDefinition> calcCap = updatedContainer.getCalculatedCapabilities();
Map<String, MapListRequirementDataDefinition> calcReg = updatedContainer.getCalculatedRequirements();
Map<String, MapCapabilityProperty> calcCapProp = updatedContainer.getCalculatedCapabilitiesProperties();
-
Map<String, List<CapabilityDefinition>> additionalCap = componentInstance.getCapabilities();
Map<String, List<RequirementDefinition>> additionalReq = componentInstance.getRequirements();
-
- MapListCapabilityDataDefinition allCalculatedCap = calcCap == null || !calcCap.containsKey(componentInstanceData.getUniqueId()) ? new MapListCapabilityDataDefinition() : calcCap.get(componentInstanceData.getUniqueId());
+ MapListCapabilityDataDefinition allCalculatedCap =
+ calcCap == null || !calcCap.containsKey(componentInstanceData.getUniqueId()) ? new MapListCapabilityDataDefinition()
+ : calcCap.get(componentInstanceData.getUniqueId());
/******** capability ****************************/
- StorageOperationStatus status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceData.getUniqueId());
+ StorageOperationStatus status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(),
+ EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceData.getUniqueId());
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ",
+ componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status);
return Either.right(status);
}
if (additionalCap != null && !additionalCap.isEmpty()) {
Map<String, ListCapabilityDataDefinition> serverCap = additionalCap.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, en -> new ListCapabilityDataDefinition(en.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))));
+ .collect(Collectors.toMap(Map.Entry::getKey,
+ en -> new ListCapabilityDataDefinition(en.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))));
serverCap.entrySet().forEach(entryPerType -> entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> {
cap.addToPath(componentInstance.getUniqueId());
allCalculatedCap.add(entryPerType.getKey(), cap);
}));
- addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId());
+ addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES,
+ VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId());
/******** capability property ****************************/
status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
@@ -259,11 +266,9 @@ public class NodeTemplateOperation extends BaseOperation {
componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status);
return Either.right(status);
}
-
MapCapabilityProperty allCalculatedCapProp =
calcCapProp == null || !calcCapProp.containsKey(componentInstanceData.getUniqueId()) ? new MapCapabilityProperty()
: calcCapProp.get(componentInstanceData.getUniqueId());
-
additionalCap.forEach((s, caps) -> {
if (caps != null && !caps.isEmpty()) {
MapPropertiesDataDefinition dataToCreate;
@@ -286,45 +291,58 @@ public class NodeTemplateOperation extends BaseOperation {
addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
VertexTypeEnum.CALCULATED_CAP_PROPERTIES, allCalculatedCapProp, componentInstance.getUniqueId());
}
-
/******** Requirements property ****************************/
if (additionalReq != null && !additionalReq.isEmpty()) {
- MapListRequirementDataDefinition allCalculatedReq = calcReg == null || !calcReg.containsKey(componentInstanceData.getUniqueId()) ? new MapListRequirementDataDefinition() : calcReg.get(componentInstanceData.getUniqueId());
- status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceData.getUniqueId());
+ MapListRequirementDataDefinition allCalculatedReq =
+ calcReg == null || !calcReg.containsKey(componentInstanceData.getUniqueId()) ? new MapListRequirementDataDefinition()
+ : calcReg.get(componentInstanceData.getUniqueId());
+ status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS,
+ VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceData.getUniqueId());
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated Requirements for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated Requirements for instance {} in container {}. error {] ",
+ componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status);
return Either.right(status);
}
Map<String, ListRequirementDataDefinition> serverReq = additionalReq.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, en -> new ListRequirementDataDefinition(en.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))));
+ .collect(Collectors.toMap(Map.Entry::getKey, en -> new ListRequirementDataDefinition(
+ en.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))));
serverReq.entrySet().forEach(entryPerType -> entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> {
cap.addToPath(componentInstance.getUniqueId());
allCalculatedReq.add(entryPerType.getKey(), cap);
}));
- addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId());
+ addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS,
+ VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId());
}
- Either<ToscaElement, StorageOperationStatus> updatedComponentInstanceRes = topologyTemplateOperation.getToscaElement(updatedContainer.getUniqueId());
+ Either<ToscaElement, StorageOperationStatus> updatedComponentInstanceRes = topologyTemplateOperation
+ .getToscaElement(updatedContainer.getUniqueId());
if (updatedComponentInstanceRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", updatedContainer.getName(), componentInstance.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ",
+ updatedContainer.getName(), componentInstance.getName());
Either.right(updatedComponentInstanceRes.right().value());
}
return Either.left(new ImmutablePair<>((TopologyTemplate) updatedComponentInstanceRes.left().value(), componentInstanceData.getUniqueId()));
}
- private Either<String, StorageOperationStatus> buildValidateInstanceName(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance, String instanceNumberSuffix) {
+ private Either<String, StorageOperationStatus> buildValidateInstanceName(TopologyTemplate container, ToscaElement originToscaElement,
+ ComponentInstance componentInstance, String instanceNumberSuffix) {
Either<String, StorageOperationStatus> result = null;
String instanceName = componentInstance.getName();
- if (StringUtils.isEmpty(instanceName) || instanceName.equalsIgnoreCase(originToscaElement.getName()) || componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) {
+ if (StringUtils.isEmpty(instanceName) || instanceName.equalsIgnoreCase(originToscaElement.getName())
+ || componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy
+ || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) {
instanceName = buildComponentInstanceName(instanceNumberSuffix, instanceName);
} else if (!isUniqueInstanceName(container, componentInstance.getName())) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create component instance with name {} on component container {}. The instance with the same name already exists. ", componentInstance.getName(), container.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to create component instance with name {} on component container {}. The instance with the same name already exists. ",
+ componentInstance.getName(), container.getName());
result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS);
}
if (result == null) {
@@ -333,27 +351,28 @@ public class NodeTemplateOperation extends BaseOperation {
return result;
}
- private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addServiceInstancePropertiesToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance) {
+ private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addServiceInstancePropertiesToProxyServiceInstance(
+ TopologyTemplate updatedContainer, ComponentInstance componentInstance) {
List<PropertyDefinition> propertiesList = componentInstance.getProperties();
if (propertiesList != null && !propertiesList.isEmpty()) {
Map<String, PropertyDataDefinition> propertiesMap = propertiesList.stream().map(PropertyDataDefinition::new)
- .collect(Collectors.toMap(
- PropertyDataDefinition::getName, i -> i));
+ .collect(Collectors.toMap(
+ PropertyDataDefinition::getName, i -> i));
MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(propertiesMap);
Map<String, MapPropertiesDataDefinition> instPropertiesMap = new HashMap<>();
instPropertiesMap.put(componentInstance.getUniqueId(), instProperties);
updatedContainer.setInstProperties(instPropertiesMap);
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes = janusGraphDao
.getVertexById(updatedContainer.getUniqueId(), JsonParseFlagEnum.NoParse);
- if(getToscaElementRes.isLeft()){
- deleteToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), EdgeLabelEnum.INST_PROPERTIES,
- VertexTypeEnum.INST_PROPERTIES, componentInstance.getUniqueId());
- }
+ if (getToscaElementRes.isLeft()) {
+ deleteToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), EdgeLabelEnum.INST_PROPERTIES,
+ VertexTypeEnum.INST_PROPERTIES, componentInstance.getUniqueId());
+ }
StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(),
- EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, instProperties,
- componentInstance.getUniqueId());
+ EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, instProperties,
+ componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
@@ -363,23 +382,24 @@ public class NodeTemplateOperation extends BaseOperation {
return Either.left(new ImmutablePair<>(updatedContainer, componentInstance.getUniqueId()));
}
- private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addServiceInstanceInputsToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance) {
+ private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addServiceInstanceInputsToProxyServiceInstance(
+ TopologyTemplate updatedContainer, ComponentInstance componentInstance) {
List<InputDefinition> inputsList = componentInstance.getInputs();
if (CollectionUtils.isNotEmpty(inputsList)) {
Map<String, PropertyDataDefinition> inputsMap = inputsList.stream().map(
- PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i));
+ PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i));
MapPropertiesDataDefinition instInputs = new MapPropertiesDataDefinition(inputsMap);
Map<String, MapPropertiesDataDefinition> instInputsMap = new HashMap<>();
instInputsMap.put(componentInstance.getUniqueId(), instInputs);
updatedContainer.setInstInputs(instInputsMap);
StorageOperationStatus status =
- addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(),
- EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instInputs,
- componentInstance.getUniqueId());
- if(status != StorageOperationStatus.OK) {
+ addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(),
+ EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instInputs,
+ componentInstance.getUniqueId());
+ if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
}
@@ -387,11 +407,13 @@ public class NodeTemplateOperation extends BaseOperation {
return Either.left(new ImmutablePair<>(updatedContainer, componentInstance.getUniqueId()));
}
- private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addComponentInstanceInterfacesToTopologyTemplate(TopologyTemplate updatedContainer, ComponentInstance componentInstance) {
+ private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addComponentInstanceInterfacesToTopologyTemplate(
+ TopologyTemplate updatedContainer, ComponentInstance componentInstance) {
Map<String, Object> interfaces = componentInstance.getInterfaces();
- if(MapUtils.isNotEmpty(interfaces)){
- Map<String, InterfaceDataDefinition> interfacesMap = interfaces.entrySet().stream().collect(Collectors.toMap(e -> ((InterfaceDataDefinition) e.getValue()).getUniqueId(), e -> (InterfaceDataDefinition) e.getValue()));
+ if (MapUtils.isNotEmpty(interfaces)) {
+ Map<String, InterfaceDataDefinition> interfacesMap = interfaces.entrySet().stream()
+ .collect(Collectors.toMap(e -> ((InterfaceDataDefinition) e.getValue()).getUniqueId(), e -> (InterfaceDataDefinition) e.getValue()));
MapInterfaceDataDefinition instInterfaces = new MapInterfaceDataDefinition(interfacesMap);
Map<String, MapInterfaceDataDefinition> instInterfacesMap = new HashMap<>();
@@ -399,11 +421,11 @@ public class NodeTemplateOperation extends BaseOperation {
updatedContainer.setComponentInstInterfaces(instInterfacesMap);
StorageOperationStatus status =
- addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(),
- EdgeLabelEnum.INST_INTERFACES, VertexTypeEnum.INST_INTERFACES, instInterfaces,
- componentInstance.getUniqueId());
+ addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(),
+ EdgeLabelEnum.INST_INTERFACES, VertexTypeEnum.INST_INTERFACES, instInterfaces,
+ componentInstance.getUniqueId());
- if(status != StorageOperationStatus.OK) {
+ if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
}
@@ -412,26 +434,29 @@ public class NodeTemplateOperation extends BaseOperation {
}
public Either<TopologyTemplate, StorageOperationStatus> addComponentInstanceToTopologyTemplate(
- TopologyTemplate container, ToscaElement originToscaElement,
- ComponentInstanceDataDefinition componentInstance, GraphVertex metadataVertex, boolean allowDeleted,
- User user) {
+ TopologyTemplate container, ToscaElement originToscaElement,
+ ComponentInstanceDataDefinition componentInstance, GraphVertex metadataVertex, boolean allowDeleted,
+ User user) {
Either<TopologyTemplate, StorageOperationStatus> result = null;
Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
String containerComponentId = container.getUniqueId();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to create component instance {} in component {}", componentInstance, containerComponentId);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to create component instance {} in component {}", componentInstance,
+ containerComponentId);
String instOriginComponentId = componentInstance.getComponentUid();
Either<GraphVertex, JanusGraphOperationStatus> updateElement = null;
Boolean isDeleted = (Boolean) originToscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED);
if (!allowDeleted && (isDeleted != null) && isDeleted) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance", instOriginComponentId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance", instOriginComponentId);
result = Either.right(StorageOperationStatus.INVALID_ID);
}
Boolean isArchived = originToscaElement.isArchived();
if (isArchived != null && isArchived) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create instance {}. Origin {} component is archived . ", componentInstance.getName(), originToscaElement.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create instance {}. Origin {} component is archived . ",
+ componentInstance.getName(), originToscaElement.getName());
result = Either.right(StorageOperationStatus.COMPONENT_IS_ARCHIVED);
}
@@ -441,12 +466,15 @@ public class NodeTemplateOperation extends BaseOperation {
topologyTemplateOperation.fillToscaElementVertexData(metadataVertex, container, JsonParseFlagEnum.ParseAll);
updateElement = janusGraphDao.updateVertex(metadataVertex);
if (updateElement.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstance.getName());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(),
+ componentInstance.getName());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
}
}
if (result == null) {
- Either<GraphVertex, StorageOperationStatus> addToscaDataRes = addComponentInstanceToscaDataToContainerComponent(originToscaElement, componentInstance, updateElement.left().value());
+ Either<GraphVertex, StorageOperationStatus> addToscaDataRes = addComponentInstanceToscaDataToContainerComponent(originToscaElement,
+ componentInstance, updateElement.left().value());
if (addToscaDataRes.isRight()) {
result = Either.right(addToscaDataRes.right().value());
}
@@ -459,7 +487,8 @@ public class NodeTemplateOperation extends BaseOperation {
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
if (updateContainerComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", container.getName(), componentInstance.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ",
+ container.getName(), componentInstance.getName());
result = Either.right(updateContainerComponentRes.right().value());
}
}
@@ -469,13 +498,16 @@ public class NodeTemplateOperation extends BaseOperation {
return result;
}
- public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance) {
+ public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(
+ TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance) {
Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null;
Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
String containerComponentId = container.getUniqueId();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstance, containerComponentId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstance,
+ containerComponentId);
ComponentInstanceDataDefinition componentInstanceData = null;
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
@@ -488,37 +520,45 @@ public class NodeTemplateOperation extends BaseOperation {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
if (result == null) {
- componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), componentInstance.getName(), false, originToscaElement);
+ componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), componentInstance.getName(),
+ false, originToscaElement);
container.addComponentInstance(componentInstanceData);
metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll);
Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao
.updateVertex(metadataVertex.left().value());
if (updateElement.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstance.getName());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(),
+ componentInstance.getName());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
}
}
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
if (updateContainerComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", container.getName(), componentInstance.getName());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ",
+ container.getName(), componentInstance.getName());
result = Either.right(updateContainerComponentRes.right().value());
}
}
if (result == null) {
- result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceData.getUniqueId()));
+ result = Either
+ .left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceData.getUniqueId()));
}
return result;
}
- public Either<TopologyTemplate, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ComponentParametersView filter) {
+ public Either<TopologyTemplate, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container,
+ ComponentParametersView filter) {
Either<TopologyTemplate, StorageOperationStatus> result = null;
Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
String containerComponentId = container.getUniqueId();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata of container component {}", containerComponentId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata of container component {}", containerComponentId);
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
@@ -552,13 +592,16 @@ public class NodeTemplateOperation extends BaseOperation {
return result;
}
- public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(TopologyTemplate container, String componentInstanceId) {
+ public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(
+ TopologyTemplate container, String componentInstanceId) {
Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null;
Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
String containerComponentId = container.getUniqueId();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstanceId, containerComponentId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstanceId,
+ containerComponentId);
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
@@ -576,7 +619,8 @@ public class NodeTemplateOperation extends BaseOperation {
containerV = metadataVertex.left().value();
StorageOperationStatus status = removeRelationsOfInstance(container, componentInstanceId, containerV);
if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete relation for component instance {} in container. error {}", componentInstanceId, container.getUniqueId(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete relation for component instance {} in container. error {}",
+ componentInstanceId, container.getUniqueId(), status);
result = Either.right(status);
}
@@ -584,14 +628,18 @@ public class NodeTemplateOperation extends BaseOperation {
topologyTemplateOperation.fillToscaElementVertexData(containerV, container, JsonParseFlagEnum.ParseAll);
Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(containerV);
if (updateElement.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstanceId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(),
+ componentInstanceId);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
}
}
if (result == null) {
StorageOperationStatus status = deleteComponentInstanceToscaDataFromContainerComponent(containerV, componentInstanceId);
if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete data for instance {} in container {}. error {] ", componentInstanceId, container.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete data for instance {} in container {}. error {] ", componentInstanceId,
+ container.getUniqueId(), status);
return Either.right(status);
}
ComponentInstance componentInstance = new ComponentInstance(removedComponentInstance);
@@ -601,7 +649,9 @@ public class NodeTemplateOperation extends BaseOperation {
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
if (updateContainerComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} after deleting the component instance {}. ", container.getName(), componentInstanceId);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to fetch updated topology template {} after deleting the component instance {}. ", container.getName(),
+ componentInstanceId);
result = Either.right(updateContainerComponentRes.right().value());
}
}
@@ -616,27 +666,31 @@ public class NodeTemplateOperation extends BaseOperation {
if (composition != null) {
Map<String, RelationshipInstDataDefinition> relations = composition.getRelations();
if (MapUtils.isNotEmpty(relations)) {
- Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
+ Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(
+ containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (capResult.isRight()) {
return capResult.right().value();
}
Map<String, MapListCapabilityDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
- Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
+ Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(
+ containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capFullResult.isRight()) {
return capFullResult.right().value();
}
Map<String, MapListCapabilityDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight();
- Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(
+ containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (reqResult.isRight()) {
return reqResult.right().value();
}
Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight();
- Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(
+ containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
if (reqResult.isRight()) {
return reqResult.right().value();
}
@@ -649,12 +703,16 @@ public class NodeTemplateOperation extends BaseOperation {
if (relationToDelete.getFromId().equals(ciToRemove) || relationToDelete.getToId().equals(ciToRemove)) {
iterator.remove();
if (relationToDelete.getFromId().equals(ciToRemove)) {
- updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, ciToRemove, relationToDelete, null);
- updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, relationToDelete.getToId(), relationToDelete, null);
+ updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, ciToRemove,
+ relationToDelete, null);
+ updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, relationToDelete.getToId(),
+ relationToDelete, null);
}
if (relationToDelete.getToId().equals(ciToRemove)) {
- updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, relationToDelete.getFromId(), relationToDelete, null);
- updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, ciToRemove, relationToDelete, null);
+ updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement,
+ relationToDelete.getFromId(), relationToDelete, null);
+ updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, ciToRemove, relationToDelete,
+ null);
}
}
}
@@ -665,85 +723,119 @@ public class NodeTemplateOperation extends BaseOperation {
}
private StorageOperationStatus deleteComponentInstanceToscaDataFromContainerComponent(GraphVertex containerV, String componentInstanceId) {
- StorageOperationStatus status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceId);
+ StorageOperationStatus status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES,
+ VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ",
+ componentInstanceId, containerV.getUniqueId(), status);
return status;
}
- status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceId);
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
+ VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceId,
+ containerV.getUniqueId(), status);
return status;
}
- status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceId);
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS,
+ VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated requirement for instance {} in container {}. error {] ",
+ componentInstanceId, containerV.getUniqueId(), status);
return status;
}
- status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, componentInstanceId);
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES,
+ VertexTypeEnum.FULLFILLED_CAPABILITIES, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled capabilities for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled capabilities for instance {} in container {}. error {] ",
+ componentInstanceId, containerV.getUniqueId(), status);
return status;
}
- status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, componentInstanceId);
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS,
+ VertexTypeEnum.FULLFILLED_REQUIREMENTS, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ",
+ componentInstanceId, containerV.getUniqueId(), status);
return status;
}
- status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, componentInstanceId);
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES,
+ componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove attributes for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove attributes for instance {} in container {}. error {] ",
+ componentInstanceId, containerV.getUniqueId(), status);
return status;
}
- status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, componentInstanceId);
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES,
+ componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove properties for instance {} in container {}. error {] ",
+ componentInstanceId, containerV.getUniqueId(), status);
return status;
}
- status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, componentInstanceId);
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS,
+ componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance inputs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance inputs for instance {} in container {}. error {] ",
+ componentInstanceId, containerV.getUniqueId(), status);
return status;
}
- status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, componentInstanceId);
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS,
+ componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ",
+ componentInstanceId, containerV.getUniqueId(), status);
return status;
}
- status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, componentInstanceId);
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS,
+ VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance deployment artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance deployment artifacts for instance {} in container {}. error {] ",
+ componentInstanceId, containerV.getUniqueId(), status);
return status;
}
- status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS, componentInstanceId);
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS,
+ componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance artifacts for instance {} in container {}. error {] ",
+ componentInstanceId, containerV.getUniqueId(), status);
return status;
}
- status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, componentInstanceId);
+ status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF,
+ componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance external refs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance external refs for instance {} in container {}. error {] ",
+ componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INTERFACES,
- VertexTypeEnum.INST_INTERFACES, componentInstanceId);
+ VertexTypeEnum.INST_INTERFACES, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
- "Failed to remove service instance interfaces for instance {} in container {}. " +
- "error {] ", componentInstanceId, containerV.getUniqueId(), status);
+ "Failed to remove service instance interfaces for instance {} in container {}. " +
+ "error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
return StorageOperationStatus.OK;
}
- protected Either<GraphVertex, StorageOperationStatus> addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
+ protected Either<GraphVertex, StorageOperationStatus> addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement,
+ ComponentInstanceDataDefinition componentInstance,
+ GraphVertex updatedContainerVertex) {
Either<GraphVertex, StorageOperationStatus> result;
StorageOperationStatus status;
if (originToscaElement.getToscaType() == ToscaElementTypeEnum.NODE_TYPE) {
status = addComponentInstanceToscaDataToNodeTypeContainer((NodeType) originToscaElement, componentInstance, updatedContainerVertex);
} else {
- status = addComponentInstanceToscaDataToTopologyTemplateContainer((TopologyTemplate) originToscaElement, componentInstance, updatedContainerVertex);
+ status = addComponentInstanceToscaDataToTopologyTemplateContainer((TopologyTemplate) originToscaElement, componentInstance,
+ updatedContainerVertex);
}
if (status == StorageOperationStatus.OK) {
result = Either.left(updatedContainerVertex);
@@ -753,7 +845,9 @@ public class NodeTemplateOperation extends BaseOperation {
return result;
}
- private StorageOperationStatus addComponentInstanceToscaDataToTopologyTemplateContainer(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
+ private StorageOperationStatus addComponentInstanceToscaDataToTopologyTemplateContainer(TopologyTemplate originTopologyTemplate,
+ ComponentInstanceDataDefinition componentInstance,
+ GraphVertex updatedContainerVertex) {
StorageOperationStatus status;
@@ -767,7 +861,8 @@ public class NodeTemplateOperation extends BaseOperation {
MapPropertiesDataDefinition instInputs = new MapPropertiesDataDefinition(originTopologyTemplate.getInputs());
MapPropertiesDataDefinition instInputsAsProperties = turnInputsIntoProperties(instInputs);
- status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instInputsAsProperties, componentInstance.getUniqueId());
+ status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS,
+ instInputsAsProperties, componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return status;
}
@@ -787,13 +882,13 @@ public class NodeTemplateOperation extends BaseOperation {
}
private MapListCapabilityDataDefinition prepareCalculatedCapabiltyForTopologyTemplate(
- Map<String, ListCapabilityDataDefinition> capabilities,
- ComponentInstanceDataDefinition componentInstance,
- MapListCapabilityDataDefinition calculatedCap) {
- MapListCapabilityDataDefinition allCalculatedCap =
- new MapListCapabilityDataDefinition(calculatedCap);
- populateCapability(capabilities, componentInstance, allCalculatedCap);
- return allCalculatedCap;
+ Map<String, ListCapabilityDataDefinition> capabilities,
+ ComponentInstanceDataDefinition componentInstance,
+ MapListCapabilityDataDefinition calculatedCap) {
+ MapListCapabilityDataDefinition allCalculatedCap =
+ new MapListCapabilityDataDefinition(calculatedCap);
+ populateCapability(capabilities, componentInstance, allCalculatedCap);
+ return allCalculatedCap;
}
private void populateCapability(Map<String, ListCapabilityDataDefinition> capabilities,
@@ -801,15 +896,15 @@ public class NodeTemplateOperation extends BaseOperation {
MapListCapabilityDataDefinition allCalculatedCap) {
capabilities.forEach((key, value) -> {
List<CapabilityDataDefinition> listCapabilities = value.getListToscaDataDefinition()
- .stream().map(CapabilityDataDefinition::new).collect(Collectors.toList());
+ .stream().map(CapabilityDataDefinition::new).collect(Collectors.toList());
listCapabilities.forEach(cap -> {
cap.setSource(componentInstance.getComponentUid());
cap.addToPath(componentInstance.getUniqueId());
log.debug("enter populateCapability,get Capability OwnerId:{},get componentInstance UniqueId:{}",
- cap.getOwnerId(), componentInstance.getUniqueId());
+ cap.getOwnerId(), componentInstance.getUniqueId());
cap.setOwnerId(componentInstance.getUniqueId());
log.debug("enter populateCapability,get Capability OwnerName:{},get componentInstance Name:{}",
- cap.getOwnerName(), componentInstance.getName());
+ cap.getOwnerName(), componentInstance.getName());
if (cap.getOwnerName() == null || cap.getOwnerName().isEmpty()) {
cap.setOwnerName(componentInstance.getName());
}
@@ -820,26 +915,27 @@ public class NodeTemplateOperation extends BaseOperation {
}
private MapListRequirementDataDefinition prepareCalculatedRequirementForTopologyTemplate(
- Map<String, ListRequirementDataDefinition> requirements,
- ComponentInstanceDataDefinition componentInstance,
- MapListRequirementDataDefinition calculatedReqs) {
- MapListRequirementDataDefinition allCalculatedReq =
- new MapListRequirementDataDefinition(calculatedReqs);
+ Map<String, ListRequirementDataDefinition> requirements,
+ ComponentInstanceDataDefinition componentInstance,
+ MapListRequirementDataDefinition calculatedReqs) {
+ MapListRequirementDataDefinition allCalculatedReq =
+ new MapListRequirementDataDefinition(calculatedReqs);
- populateRequirement(requirements, componentInstance, allCalculatedReq);
- return allCalculatedReq;
+ populateRequirement(requirements, componentInstance, allCalculatedReq);
+ return allCalculatedReq;
}
+
private void populateRequirement(Map<String, ListRequirementDataDefinition> requirements,
ComponentInstanceDataDefinition componentInstance,
MapListRequirementDataDefinition allCalculatedReq) {
requirements.forEach((key, value) -> {
List<RequirementDataDefinition> listRequirements = value.getListToscaDataDefinition()
- .stream().map(RequirementDataDefinition::new).collect(Collectors.toList());
+ .stream().map(RequirementDataDefinition::new).collect(Collectors.toList());
listRequirements.forEach(req -> {
req.setSource(componentInstance.getComponentUid());
req.addToPath(componentInstance.getUniqueId());
log.debug("enter populateRequirement,get init Requirements OwnerId:{},get componentInstance UniqueId:{}",
- req.getOwnerId(), componentInstance.getUniqueId());
+ req.getOwnerId(), componentInstance.getUniqueId());
if (req.getOwnerId() == null || req.getOwnerId().isEmpty()) {
req.setOwnerId(componentInstance.getUniqueId());
}
@@ -853,9 +949,9 @@ public class NodeTemplateOperation extends BaseOperation {
});
}
-
-
- private StorageOperationStatus addCalculatedCapReqFromTopologyTemplate(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
+ private StorageOperationStatus addCalculatedCapReqFromTopologyTemplate(TopologyTemplate originTopologyTemplate,
+ ComponentInstanceDataDefinition componentInstance,
+ GraphVertex updatedContainerVertex) {
Map<String, MapListCapabilityDataDefinition> calculatedCapabilities = originTopologyTemplate.getCalculatedCapabilities();
MapListCapabilityDataDefinition allCalculatedCap = new MapListCapabilityDataDefinition();
@@ -872,39 +968,39 @@ public class NodeTemplateOperation extends BaseOperation {
Map<String, ListCapabilityDataDefinition> capabilities = originTopologyTemplate.getCapabilities();
if (MapUtils.isNotEmpty(capabilities)) {
allCaps = prepareCalculatedCapabiltyForTopologyTemplate(capabilities, componentInstance,
- allCalculatedCap);
+ allCalculatedCap);
} else {
allCaps = new MapListCapabilityDataDefinition(allCalculatedCap);
}
- if(!allCaps.isEmpty()) {
+ if (!allCaps.isEmpty()) {
StorageOperationStatus calculatedCapabilitiesResult =
- addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
- EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES,
- allCaps, componentInstance.getUniqueId());
+ addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
+ EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES,
+ allCaps, componentInstance.getUniqueId());
if (calculatedCapabilitiesResult != StorageOperationStatus.OK) {
return calculatedCapabilitiesResult;
}
MapListCapabilityDataDefinition fullCalculatedCap = new MapListCapabilityDataDefinition();
calculatedCapabilitiesResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
- EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES,
- fullCalculatedCap, componentInstance.getUniqueId());
+ EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES,
+ fullCalculatedCap, componentInstance.getUniqueId());
if (calculatedCapabilitiesResult != StorageOperationStatus.OK) {
return calculatedCapabilitiesResult;
}
}
Map<String, MapListRequirementDataDefinition> calculatedRequirements =
- originTopologyTemplate.getCalculatedRequirements();
+ originTopologyTemplate.getCalculatedRequirements();
MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition();
if (calculatedRequirements != null) {
calculatedRequirements.forEach((key, value) -> {
Map<String, ListRequirementDataDefinition> mapByType =
- value.getMapToscaDataDefinition();
+ value.getMapToscaDataDefinition();
mapByType.forEach((key1, value1) -> value1.getListToscaDataDefinition().stream()
- .filter(RequirementDataDefinition::isExternal).forEach(req -> {
- req.addToPath(componentInstance.getUniqueId());
- req.setExternal(false);
- allCalculatedReq.add(key1, req);
- }));
+ .filter(RequirementDataDefinition::isExternal).forEach(req -> {
+ req.addToPath(componentInstance.getUniqueId());
+ req.setExternal(false);
+ allCalculatedReq.add(key1, req);
+ }));
});
}
@@ -913,23 +1009,24 @@ public class NodeTemplateOperation extends BaseOperation {
Map<String, ListRequirementDataDefinition> requirements = originTopologyTemplate.getRequirements();
if (MapUtils.isNotEmpty(requirements)) {
allReqs = prepareCalculatedRequirementForTopologyTemplate(requirements,
- componentInstance, allCalculatedReq);
- } else
+ componentInstance, allCalculatedReq);
+ } else {
allReqs = new MapListRequirementDataDefinition(allCalculatedReq);
+ }
- if(!allReqs.isEmpty()) {
+ if (!allReqs.isEmpty()) {
StorageOperationStatus calculatedRequirementResult =
- addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
- EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS,
- allReqs, componentInstance.getUniqueId());
+ addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
+ EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS,
+ allReqs, componentInstance.getUniqueId());
if (calculatedRequirementResult != StorageOperationStatus.OK) {
return calculatedRequirementResult;
}
MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition();
calculatedRequirementResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
- EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS,
- fullCalculatedReq,
- componentInstance.getUniqueId());
+ EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS,
+ fullCalculatedReq,
+ componentInstance.getUniqueId());
if (calculatedRequirementResult != StorageOperationStatus.OK) {
return calculatedRequirementResult;
}
@@ -946,35 +1043,35 @@ public class NodeTemplateOperation extends BaseOperation {
}
}
Map<String, MapPropertiesDataDefinition> capabilitiesProperties =
- originTopologyTemplate.getCapabilitiesProperties();
+ originTopologyTemplate.getCapabilitiesProperties();
Map<String, MapPropertiesDataDefinition> updateKeyMapCapabilitiesProperties;
if (MapUtils.isNotEmpty(capabilitiesProperties)) {
updateKeyMapCapabilitiesProperties = capabilitiesProperties.entrySet().stream()
- .collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(),
- componentInstance.getUniqueId()), Entry::getValue));
- }
- else {
+ .collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(),
+ componentInstance.getUniqueId()), Entry::getValue));
+ } else {
updateKeyMapCapabilitiesProperties = new HashMap<>();
}
updateKeyMap.putAll(updateKeyMapCapabilitiesProperties);
MapCapabilityProperty mapCapabilityProperty = new MapCapabilityProperty(updateKeyMap);
- if(MapUtils.isNotEmpty(capabilitiesProperties) || MapUtils.isNotEmpty(calculatedCapabilitiesProperties )) {
+ if (MapUtils.isNotEmpty(capabilitiesProperties) || MapUtils.isNotEmpty(calculatedCapabilitiesProperties)) {
StorageOperationStatus calculatedResult =
- addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
- EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
- VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabilityProperty,
- componentInstance.getUniqueId());
+ addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
+ EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
+ VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabilityProperty,
+ componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
}
return StorageOperationStatus.OK;
}
-
- public StorageOperationStatus updateComponentInstanceRequirement(String componentId, String componentInstanceUniqueId, RequirementDataDefinition requirementDataDefinition) {
+
+ public StorageOperationStatus updateComponentInstanceRequirement(String componentId, String componentInstanceUniqueId,
+ RequirementDataDefinition requirementDataDefinition) {
Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
JanusGraphOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error);
@@ -984,8 +1081,10 @@ public class NodeTemplateOperation extends BaseOperation {
return updateComponentInstanceRequirement(componentId, componentInstanceUniqueId, requirementDataDefinition, containerV);
}
- private StorageOperationStatus updateComponentInstanceRequirement(String componentId, String componentInstanceUniqueId, RequirementDataDefinition requirementDataDefinition, GraphVertex containerV) {
- Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> existingReqs = getCalculatedRequirements(componentId);
+ private StorageOperationStatus updateComponentInstanceRequirement(String componentId, String componentInstanceUniqueId,
+ RequirementDataDefinition requirementDataDefinition, GraphVertex containerV) {
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> existingReqs = getCalculatedRequirements(
+ componentId);
if (existingReqs.isRight()) {
return existingReqs.right().value();
}
@@ -993,16 +1092,18 @@ public class NodeTemplateOperation extends BaseOperation {
if (componentInstanceRequirementsMap == null) {
return StorageOperationStatus.NOT_FOUND;
}
- ListRequirementDataDefinition listRequirementDataDefinition = componentInstanceRequirementsMap.getMapToscaDataDefinition().get(requirementDataDefinition.getCapability());
-
+ ListRequirementDataDefinition listRequirementDataDefinition = componentInstanceRequirementsMap.getMapToscaDataDefinition()
+ .get(requirementDataDefinition.getCapability());
+
listRequirementDataDefinition.getListToscaDataDefinition().stream()
- .filter(e -> requirementDataDefinition.getOwnerId().equals(e.getOwnerId()) && requirementDataDefinition.getName().equals(e.getName()))
- .forEach(r -> r.setExternal(requirementDataDefinition.isExternal()));
+ .filter(e -> requirementDataDefinition.getOwnerId().equals(e.getOwnerId()) && requirementDataDefinition.getName().equals(e.getName()))
+ .forEach(r -> r.setExternal(requirementDataDefinition.isExternal()));
return updateCalculatedReqOnGraph(componentId, containerV, existingReqs);
}
-
- private Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> getCalculatedRequirements(String componentId) {
+
+ private Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> getCalculatedRequirements(
+ String componentId) {
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> result = null;
Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
@@ -1017,46 +1118,52 @@ public class NodeTemplateOperation extends BaseOperation {
}
return result;
}
-
- private StorageOperationStatus updateCalculatedReqOnGraph(String componentId, GraphVertex containerV, Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult
- ) {
+
+ private StorageOperationStatus updateCalculatedReqOnGraph(String componentId, GraphVertex containerV,
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult
+ ) {
containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(containerV);
if (updateElement.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId,
+ updateElement.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value());
}
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update calculated requirement for container {}", containerV.getUniqueId());
- Either<GraphVertex, JanusGraphOperationStatus> status = updateOrCopyOnUpdate(reqResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
+ Either<GraphVertex, JanusGraphOperationStatus> status = updateOrCopyOnUpdate(reqResult.left().value().getLeft(), containerV,
+ EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (status.isRight()) {
JanusGraphOperationStatus error = status.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(), error);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(),
+ error);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error);
}
return StorageOperationStatus.OK;
}
-
+
private StorageOperationStatus addComponentInstanceToscaDataToNodeTypeContainer(NodeType originNodeType,
- ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
+ ComponentInstanceDataDefinition componentInstance,
+ GraphVertex updatedContainerVertex) {
StorageOperationStatus status;
- if(MapUtils.isNotEmpty(originNodeType.getProperties())){
+ if (MapUtils.isNotEmpty(originNodeType.getProperties())) {
MapPropertiesDataDefinition instProperties =
- new MapPropertiesDataDefinition(originNodeType.getProperties());
+ new MapPropertiesDataDefinition(originNodeType.getProperties());
status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_PROPERTIES,
- VertexTypeEnum.INST_PROPERTIES, instProperties, componentInstance.getUniqueId());
+ VertexTypeEnum.INST_PROPERTIES, instProperties, componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return status;
}
}
- if(MapUtils.isNotEmpty(originNodeType.getAttributes())){
+ if (MapUtils.isNotEmpty(originNodeType.getAttributes())) {
MapAttributesDataDefinition instAttributes =
- new MapAttributesDataDefinition(originNodeType.getAttributes());
+ new MapAttributesDataDefinition(originNodeType.getAttributes());
status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_ATTRIBUTES,
- VertexTypeEnum.INST_ATTRIBUTES, instAttributes, componentInstance.getUniqueId());
+ VertexTypeEnum.INST_ATTRIBUTES, instAttributes, componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return status;
}
@@ -1065,14 +1172,16 @@ public class NodeTemplateOperation extends BaseOperation {
return addCalculatedCapReqFromNodeType(originNodeType, componentInstance, updatedContainerVertex);
}
- public MapArtifactDataDefinition prepareInstDeploymentArtifactPerInstance(Map<String, ArtifactDataDefinition> deploymentArtifacts, String componentInstanceId, User user, String envType) {
+ public MapArtifactDataDefinition prepareInstDeploymentArtifactPerInstance(Map<String, ArtifactDataDefinition> deploymentArtifacts,
+ String componentInstanceId, User user, String envType) {
if (deploymentArtifacts != null && envType.equals(HEAT_VF_ENV_NAME)) {
Map<String, ArtifactDataDefinition> instDeploymentArtifacts = new HashMap<>();
deploymentArtifacts.entrySet().forEach(e -> {
ArtifactDataDefinition artifact = e.getValue();
String type = artifact.getArtifactType();
- if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
+ if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type
+ .equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
ArtifactDataDefinition artifactEnv = createArtifactPlaceHolderInfo(artifact, componentInstanceId, user, envType);
instDeploymentArtifacts.put(artifactEnv.getArtifactLabel(), artifactEnv);
}
@@ -1087,8 +1196,10 @@ public class NodeTemplateOperation extends BaseOperation {
}
@SuppressWarnings({"unchecked"})
- private ArtifactDataDefinition createArtifactPlaceHolderInfo(ArtifactDataDefinition artifactHeat, String componentId, User user, String heatEnvType) {
- Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
+ private ArtifactDataDefinition createArtifactPlaceHolderInfo(ArtifactDataDefinition artifactHeat, String componentId, User user,
+ String heatEnvType) {
+ Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getDeploymentResourceInstanceArtifacts();
if (deploymentResourceArtifacts == null) {
log.debug("no deployment artifacts are configured for generated artifacts");
return null;
@@ -1157,67 +1268,62 @@ public class NodeTemplateOperation extends BaseOperation {
* @param updatedContainerVertex
* @return
*/
- private StorageOperationStatus addCalculatedCapReqFromNodeType(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
-
+ private StorageOperationStatus addCalculatedCapReqFromNodeType(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance,
+ GraphVertex updatedContainerVertex) {
Map<String, ListCapabilityDataDefinition> capabilities = originNodeType.getCapabilities();
MapListCapabilityDataDefinition allCalculatedCap = prepareCalculatedCapabiltyForNodeType(capabilities, componentInstance);
StorageOperationStatus calculatedResult;
if (allCalculatedCap != null) {
- calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId());
-
+ calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES,
+ VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
}
Map<String, MapPropertiesDataDefinition> capabiltiesProperties = originNodeType.getCapabilitiesProperties();
if (capabiltiesProperties != null) {
- Map<String, MapPropertiesDataDefinition> updateKeyMap = capabiltiesProperties.entrySet().stream().collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(), componentInstance.getUniqueId()), Entry::getValue));
+ Map<String, MapPropertiesDataDefinition> updateKeyMap = capabiltiesProperties.entrySet().stream()
+ .collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(), componentInstance.getUniqueId()), Entry::getValue));
MapCapabilityProperty mapCapabilityProperty = new MapCapabilityProperty(updateKeyMap);
- calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabilityProperty, componentInstance.getUniqueId());
+ calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
+ VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabilityProperty, componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
}
-
MapListCapabilityDataDefinition fullCalculatedCap = new MapListCapabilityDataDefinition();
- calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId());
-
+ calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES,
+ VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
-
Map<String, ListRequirementDataDefinition> requirements = originNodeType.getRequirements();
-
MapListRequirementDataDefinition allCalculatedReq = prepareCalculatedRequirementForNodeType(requirements, componentInstance);
-
StorageOperationStatus status;
if (allCalculatedReq != null) {
- status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId());
+ status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS,
+ VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return status;
}
}
MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition();
- return addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId());
- }
-
- public static String createCapPropertyKey(String key, String instanceId) {
- StringBuffer sb = new StringBuffer(instanceId);
- sb.append(ModelConverter.CAP_PROP_DELIM).append(instanceId).append(ModelConverter.CAP_PROP_DELIM).append(key);
- return sb.toString();
+ return addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS,
+ VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId());
}
/**
- * Prepares a map of capabilities lists Produces a deep copy of the received map of capabilities Sets values to the specific fields according to received component instance
+ * Prepares a map of capabilities lists Produces a deep copy of the received map of capabilities Sets values to the specific fields according to
+ * received component instance
*
* @param capabilities
* @param componentInstance
* @return
*/
- public MapListCapabilityDataDefinition prepareCalculatedCapabiltyForNodeType(Map<String, ListCapabilityDataDefinition> capabilities, ComponentInstanceDataDefinition componentInstance) {
+ public MapListCapabilityDataDefinition prepareCalculatedCapabiltyForNodeType(Map<String, ListCapabilityDataDefinition> capabilities,
+ ComponentInstanceDataDefinition componentInstance) {
if (capabilities != null) {
MapListCapabilityDataDefinition allCalculatedCap = new MapListCapabilityDataDefinition();
-
populateCapability(capabilities, componentInstance, allCalculatedCap);
return allCalculatedCap;
}
@@ -1225,39 +1331,46 @@ public class NodeTemplateOperation extends BaseOperation {
}
/**
- * Prepares a map of requirements lists Produces a deep copy of the received map of requirements Sets values to the specific fields according to received component instance
+ * Prepares a map of requirements lists Produces a deep copy of the received map of requirements Sets values to the specific fields according to
+ * received component instance
*
* @param requirements
* @param componentInstance
* @return
*/
- public MapListRequirementDataDefinition prepareCalculatedRequirementForNodeType(Map<String, ListRequirementDataDefinition> requirements, ComponentInstanceDataDefinition componentInstance) {
+ public MapListRequirementDataDefinition prepareCalculatedRequirementForNodeType(Map<String, ListRequirementDataDefinition> requirements,
+ ComponentInstanceDataDefinition componentInstance) {
if (requirements != null) {
MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition();
-
populateRequirement(requirements, componentInstance, allCalculatedReq);
return allCalculatedReq;
}
return null;
}
- public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstanceDataDefinition componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
-
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent,
+ ComponentInstanceDataDefinition componentInstance,
+ List<GroupDefinition> groups,
+ Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
StorageOperationStatus result = null;
Map<String, GroupInstanceDataDefinition> groupInstanceToCreate = new HashMap<>();
if (groupInstancesArtifacts != null && CollectionUtils.isNotEmpty(groups)) {
for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts : groupInstancesArtifacts.entrySet()) {
Optional<GroupDefinition> groupOptional = groups.stream().filter(g -> g.getUniqueId().equals(groupArtifacts.getKey())).findFirst();
if (groupOptional.isPresent()) {
- GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition((GroupDataDefinition) groupOptional.get(), (ComponentInstanceDataDefinition) componentInstance, null);
- groupInstance.setGroupInstanceArtifacts(groupArtifacts.getValue().stream().map(ArtifactDataDefinition::getUniqueId).collect(Collectors.toList()));
- groupInstance.setGroupInstanceArtifactsUuid(groupArtifacts.getValue().stream().map(ArtifactDataDefinition::getArtifactUUID).collect(Collectors.toList()));
+ GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition((GroupDataDefinition) groupOptional.get(),
+ (ComponentInstanceDataDefinition) componentInstance, null);
+ groupInstance.setGroupInstanceArtifacts(
+ groupArtifacts.getValue().stream().map(ArtifactDataDefinition::getUniqueId).collect(Collectors.toList()));
+ groupInstance.setGroupInstanceArtifactsUuid(
+ groupArtifacts.getValue().stream().map(ArtifactDataDefinition::getArtifactUUID).collect(Collectors.toList()));
groupInstanceToCreate.put(groupInstance.getName(), groupInstance);
}
}
}
if (MapUtils.isNotEmpty(groupInstanceToCreate)) {
- result = addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, new MapDataDefinition<>(groupInstanceToCreate), componentInstance.getUniqueId());
+ result = addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS,
+ VertexTypeEnum.INST_GROUPS, new MapDataDefinition<>(groupInstanceToCreate), componentInstance.getUniqueId());
}
if (result == null) {
result = StorageOperationStatus.OK;
@@ -1265,14 +1378,14 @@ public class NodeTemplateOperation extends BaseOperation {
return result;
}
- private ComponentInstanceDataDefinition buildComponentInstanceDataDefinition(ComponentInstance resourceInstance, String containerComponentId, String instanceNewName, boolean generateUid, ToscaElement originToscaElement) {
+ private ComponentInstanceDataDefinition buildComponentInstanceDataDefinition(ComponentInstance resourceInstance, String containerComponentId,
+ String instanceNewName, boolean generateUid,
+ ToscaElement originToscaElement) {
String ciOriginComponentUid = resourceInstance.getComponentUid();
-
if (!ValidationUtils.validateStringNotEmpty(resourceInstance.getCustomizationUUID())) {
resourceInstance.setCustomizationUUID(generateCustomizationUUID());
}
ComponentInstanceDataDefinition dataDefinition = new ComponentInstanceDataDefinition(resourceInstance);
-
Long creationDate = resourceInstance.getCreationTime();
Long modificationTime;
if (creationDate == null) {
@@ -1288,36 +1401,44 @@ public class NodeTemplateOperation extends BaseOperation {
dataDefinition.setName(instanceNewName);
resourceInstance.setName(instanceNewName);
}
- if (StringUtils.isNotEmpty(dataDefinition.getName()))
+ if (StringUtils.isNotEmpty(dataDefinition.getName())) {
dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(dataDefinition.getName()));
+ }
dataDefinition.setIcon(resourceInstance.getIcon());
if (generateUid) {
- dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(containerComponentId, ciOriginComponentUid, dataDefinition.getNormalizedName()));
+ dataDefinition.setUniqueId(
+ UniqueIdBuilder.buildResourceInstanceUniuqeId(containerComponentId, ciOriginComponentUid, dataDefinition.getNormalizedName()));
resourceInstance.setUniqueId(dataDefinition.getUniqueId());
}
- if (StringUtils.isEmpty(dataDefinition.getComponentVersion()) && originToscaElement != null)
+ if (StringUtils.isEmpty(dataDefinition.getComponentVersion()) && originToscaElement != null) {
dataDefinition.setComponentVersion((String) originToscaElement.getMetadataValue(JsonPresentationFields.VERSION));
- if (StringUtils.isEmpty(dataDefinition.getComponentName()) && originToscaElement != null)
+ }
+ if (StringUtils.isEmpty(dataDefinition.getComponentName()) && originToscaElement != null) {
dataDefinition.setComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.NAME));
- if (originToscaElement != null && dataDefinition.getToscaComponentName() == null)
+ }
+ if (originToscaElement != null && dataDefinition.getToscaComponentName() == null) {
dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
+ }
if (dataDefinition.getOriginType() == null && originToscaElement != null) {
ResourceTypeEnum resourceType = originToscaElement.getResourceType();
OriginTypeEnum originType = OriginTypeEnum.findByValue(resourceType.name());
dataDefinition.setOriginType(originType);
}
- if (dataDefinition.getOriginType() == OriginTypeEnum.ServiceProxy)
+ if (dataDefinition.getOriginType() == OriginTypeEnum.ServiceProxy) {
dataDefinition.setIsProxy(true);
-
+ }
return dataDefinition;
}
private Boolean isUniqueInstanceName(TopologyTemplate container, String instanceName) {
Boolean isUniqueName = true;
try {
- isUniqueName = container.getComponentInstances().values().stream().noneMatch(ci -> ci.getName() != null && ci.getName().equals(instanceName));
+ isUniqueName = container.getComponentInstances().values().stream()
+ .noneMatch(ci -> ci.getName() != null && ci.getName().equals(instanceName));
} catch (Exception e) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during fetching component instance with name {} from component container {}. {} ", instanceName, container.getName(), e.getMessage());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Exception occured during fetching component instance with name {} from component container {}. {} ", instanceName,
+ container.getName(), e.getMessage());
}
return isUniqueName;
}
@@ -1326,10 +1447,12 @@ public class NodeTemplateOperation extends BaseOperation {
return instanceName + " " + (instanceSuffixNumber == null ? 0 : instanceSuffixNumber);
}
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId, RequirementCapabilityRelDef relation) {
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId,
+ RequirementCapabilityRelDef relation) {
List<RequirementCapabilityRelDef> relations = new ArrayList<>();
relations.add(relation);
- Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances = associateResourceInstances(component, componentId, relations);
+ Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances = associateResourceInstances(component,
+ componentId, relations);
if (associateResourceInstances.isRight()) {
return Either.right(associateResourceInstances.right().value());
}
@@ -1337,45 +1460,41 @@ public class NodeTemplateOperation extends BaseOperation {
}
@SuppressWarnings({"unchecked"})
- public <T extends ToscaDataDefinition> Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId, List<RequirementCapabilityRelDef> relations) {
-
- Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ public <T extends ToscaDataDefinition> Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(
+ Component component, String componentId, List<RequirementCapabilityRelDef> relations) {
+ Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
JanusGraphOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
GraphVertex containerV = containerVEither.left().value();
- Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
+ Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(
+ containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
-
}
Map<String, MapListCapabilityDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
-
- Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
+ Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(
+ containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
-
}
Map<String, MapListCapabilityDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight();
-
- Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(
+ containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (reqResult.isRight()) {
return Either.right(reqResult.right().value());
}
Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight();
-
- Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(
+ containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
if (reqResult.isRight()) {
return Either.right(reqResult.right().value());
}
Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight();
-
Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson();
CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
-
StorageOperationStatus status;
List<RequirementCapabilityRelDef> relationsList = new ArrayList<>();
for (RequirementCapabilityRelDef relation : relations) {
@@ -1384,31 +1503,35 @@ public class NodeTemplateOperation extends BaseOperation {
String toNode = relation.getToNode();
List<CapabilityRequirementRelationship> relationships = relation.getRelationships();
if (relationships == null || relationships.isEmpty()) {
- BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode);
- loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATION.getName(),"componentId: "+componentId+" No requirement definition sent in order to set the relation between: "+fromNode+" to: "+toNode);
+ BeEcompErrorManager.getInstance()
+ .logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement definition sent in order to set the relation between {} to {}", fromNode,
+ toNode);
+ loggerSupportability.log(LogLevel.INFO, LoggerSupportabilityActions.CREATE_RELATION.getName(),
+ "componentId: " + componentId + " No requirement definition sent in order to set the relation between: " + fromNode + " to: "
+ + toNode);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
}
-
for (final CapabilityRequirementRelationship relationship : relationships) {
final String requirement = relationship.getRelation().getRequirement();
-
- Either<Map<JsonPresentationFields, T>, StorageOperationStatus> associateRes = connectInstancesInContainer(fromNode, toNode, relationship.getRelation(), relation.isOriginUI(), calculatedCapabilty, calculatedRequirement,
- fullFilledCapabilty, fullfilledRequirement, compositionDataDefinition, containerV.getUniqueId());
-
-
+ Either<Map<JsonPresentationFields, T>, StorageOperationStatus> associateRes = connectInstancesInContainer(fromNode, toNode,
+ relationship.getRelation(), relation.isOriginUI(), calculatedCapabilty, calculatedRequirement, fullFilledCapabilty,
+ fullfilledRequirement, compositionDataDefinition, containerV.getUniqueId());
if (associateRes.isRight()) {
status = associateRes.right().value();
- BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
- loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATIONS.name(),
- StatusCode.ERROR,"missing relationship: "+fromNode,"ComopnentId: "+componentId);
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status);
+ BeEcompErrorManager.getInstance()
+ .logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
+ loggerSupportability.log(LogLevel.INFO, LoggerSupportabilityActions.CREATE_RELATIONS.name(), StatusCode.ERROR,
+ "missing relationship: " + fromNode, "ComopnentId: " + componentId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate resource instance {} to resource instance {}. status is {}",
+ fromNode, toNode, status);
return Either.right(status);
}
-
final Map<JsonPresentationFields, T> relationshipFieldsMap = associateRes.left().value();
- final RelationshipInstDataDefinition relationshipInstData =
- (RelationshipInstDataDefinition) relationshipFieldsMap.get(JsonPresentationFields.RELATIONSHIP);
+ final RelationshipInstDataDefinition relationshipInstData = (RelationshipInstDataDefinition) relationshipFieldsMap
+ .get(JsonPresentationFields.RELATIONSHIP);
createRelationshipInterfaces(relationship.getOperations()).ifPresent(relationshipInstData::setInterfaces);
RelationshipImpl relationshipImplResult = new RelationshipImpl();
relationshipImplResult.setType(relationshipInstData.getType());
@@ -1426,15 +1549,18 @@ public class NodeTemplateOperation extends BaseOperation {
capReqRel.setRequirement((RequirementDataDefinition) relationshipFieldsMap.get(JsonPresentationFields.REQUIREMENT));
capReqRel.setOperations(relationship.getOperations());
relationshipsResult.add(capReqRel);
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "update customization UUID for from CI {} and to CI {}", relation.getFromNode(),
+ relation.getToNode());
status = updateCustomizationUUID(relation.getFromNode(), compositionDataDefinition);
if (status != StorageOperationStatus.OK) {
- loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATIONS.name(),StatusCode.ERROR,"ERROR while update customization UUID for from CI "+relation.getFromNode()+" and to CI: "+relation.getToNode());
+ loggerSupportability.log(LogLevel.INFO, LoggerSupportabilityActions.CREATE_RELATIONS.name(), StatusCode.ERROR,
+ "ERROR while update customization UUID for from CI " + relation.getFromNode() + " and to CI: " + relation.getToNode());
return Either.right(status);
}
status = updateCustomizationUUID(relation.getToNode(), compositionDataDefinition);
if (status != StorageOperationStatus.OK) {
- loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATIONS.name(),StatusCode.ERROR,"ERROR while update customization UUID for from CI "+relation.getFromNode()+" and to CI: "+relation.getToNode());
+ loggerSupportability.log(LogLevel.INFO, LoggerSupportabilityActions.CREATE_RELATIONS.name(), StatusCode.ERROR,
+ "ERROR while update customization UUID for from CI " + relation.getFromNode() + " and to CI: " + relation.getToNode());
return Either.right(status);
}
}
@@ -1449,9 +1575,7 @@ public class NodeTemplateOperation extends BaseOperation {
return Either.left(relationsList);
}
- private Optional<ListDataDefinition<InterfaceDataDefinition>> createRelationshipInterfaces(
- final List<OperationUi> operationList) {
-
+ private Optional<ListDataDefinition<InterfaceDataDefinition>> createRelationshipInterfaces(final List<OperationUi> operationList) {
if (CollectionUtils.isEmpty(operationList)) {
return Optional.empty();
}
@@ -1468,8 +1592,8 @@ public class NodeTemplateOperation extends BaseOperation {
final InterfaceDataDefinition interfaceDataDefinition = new InterfaceDataDefinition();
interfaceDataDefinition.setType(interfaceType);
if (CollectionUtils.isNotEmpty(operationList)) {
- final Map<String, OperationDataDefinition> operationMap =
- operationList.stream().collect(Collectors.toMap(OperationUi::getOperationType, this::createOperation));
+ final Map<String, OperationDataDefinition> operationMap = operationList.stream()
+ .collect(Collectors.toMap(OperationUi::getOperationType, this::createOperation));
interfaceDataDefinition.setOperations(operationMap);
}
return interfaceDataDefinition;
@@ -1493,17 +1617,19 @@ public class NodeTemplateOperation extends BaseOperation {
});
operationDataDefinition.setInputs(inputs);
}
-
return operationDataDefinition;
}
- private StorageOperationStatus updateAllAndCalculatedCapReqOnGraph(String componentId, GraphVertex containerV, Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult,
- Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult, Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult,
+ private StorageOperationStatus updateAllAndCalculatedCapReqOnGraph(String componentId, GraphVertex containerV,
+ Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult,
+ Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult,
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult,
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult) {
containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(containerV);
if (updateElement.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId,
+ updateElement.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value());
}
// update cap/req jsons, fulfilled cap/req jsons!!!!!
@@ -1512,55 +1638,56 @@ public class NodeTemplateOperation extends BaseOperation {
status = updateOrCopyOnUpdate(capResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (status.isRight()) {
JanusGraphOperationStatus error = status.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated capabilty for container {} error {}", containerV.getUniqueId(), error);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated capabilty for container {} error {}", containerV.getUniqueId(),
+ error);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error);
}
-
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update calculated requirement for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(reqResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (status.isRight()) {
JanusGraphOperationStatus error = status.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(), error);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(),
+ error);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error);
}
-
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update fullfilled capabilty for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(capFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (status.isRight()) {
JanusGraphOperationStatus error = status.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled capabilty for container {} error {}", containerV.getUniqueId(), error);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled capabilty for container {} error {}", containerV.getUniqueId(),
+ error);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error);
}
-
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update fullfilled requirement for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(reqFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
if (status.isRight()) {
JanusGraphOperationStatus error = status.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled requirement for container {} error {}", containerV.getUniqueId(), error);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled requirement for container {} error {}",
+ containerV.getUniqueId(), error);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error);
}
return StorageOperationStatus.OK;
}
@SuppressWarnings({"unchecked"})
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId,
+ RequirementCapabilityRelDef requirementDef) {
if (requirementDef.getRelationships() == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation pair in request [ {} ]", requirementDef);
return Either.right(StorageOperationStatus.BAD_REQUEST);
}
-
String fromResInstanceUid = requirementDef.getFromNode();
String toResInstanceUid = requirementDef.getToNode();
-
- Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
JanusGraphOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
GraphVertex containerV = containerVEither.left().value();
-
// DE191707 - validations
Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson();
CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
@@ -1569,60 +1696,60 @@ public class NodeTemplateOperation extends BaseOperation {
if (ciFrom == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "FROM instance {} isn't under container {}", fromResInstanceUid, componentId);
return Either.right(StorageOperationStatus.NOT_FOUND);
-
}
ComponentInstanceDataDefinition ciTo = componentInstances.get(toResInstanceUid);
if (ciFrom == ciTo) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "TO instance {} isn't under container {}", toResInstanceUid, componentId);
return Either.right(StorageOperationStatus.NOT_FOUND);
-
}
Map<String, RelationshipInstDataDefinition> relations = compositionDataDefinition.getRelations();
-
List<CapabilityRequirementRelationship> relationPairList = requirementDef.getRelationships();
- Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
+ Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(
+ containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
}
Map<String, MapListCapabilityDataDefinition> calculatedCapability = capResult.left().value().getRight();
-
- Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
+ Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(
+ containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
-
}
Map<String, MapListCapabilityDataDefinition> fulfilledCapability = capFullResult.left().value().getRight();
-
- Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(
+ containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (reqResult.isRight()) {
return Either.right(reqResult.right().value());
}
Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight();
-
- Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(
+ containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
if (reqResult.isRight()) {
return Either.right(reqResult.right().value());
}
Map<String, MapListRequirementDataDefinition> fulfilledRequirement = reqFullResult.left().value().getRight();
-
for (CapabilityRequirementRelationship relationPair : relationPairList) {
Iterator<Entry<String, RelationshipInstDataDefinition>> iterator = relations.entrySet().iterator();
boolean isDeleted = false;
while (iterator.hasNext()) {
Entry<String, RelationshipInstDataDefinition> entryInJson = iterator.next();
RelationshipInstDataDefinition relationInJson = entryInJson.getValue();
- if (relationInJson.getFromId().equals(fromResInstanceUid) && relationInJson.getToId().equals(toResInstanceUid) && relationInJson.getUniqueId().equals(relationPair.getRelation().getId())) {
+ if (relationInJson.getFromId().equals(fromResInstanceUid) && relationInJson.getToId().equals(toResInstanceUid) && relationInJson
+ .getUniqueId().equals(relationPair.getRelation().getId())) {
if (relationPair.getRelation().equalsTo(relationInJson)) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Remove relation from {} to {} capability {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(), relationInJson.getCapabilityOwnerId(),
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Remove relation from {} to {} capability {} capOwnerId {} reqOwnerId {} ",
+ toResInstanceUid, componentId, relationInJson.getType(), relationInJson.getCapabilityOwnerId(),
relationInJson.getRequirementOwnerId());
iterator.remove();
-
// update calculated cap/req
- StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapability, fulfilledCapability, toResInstanceUid, relationInJson, relationPair);
+ StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapability, fulfilledCapability,
+ toResInstanceUid, relationInJson, relationPair);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
- status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fulfilledRequirement, fromResInstanceUid, relationInJson, relationPair);
+ status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fulfilledRequirement, fromResInstanceUid,
+ relationInJson, relationPair);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
@@ -1631,8 +1758,9 @@ public class NodeTemplateOperation extends BaseOperation {
}
}
if (!isDeleted) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation to delete from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationPair.getCapability(),
- relationPair.getRelation().getCapabilityOwnerId(), relationPair.getRelation().getRequirementOwnerId());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation to delete from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ",
+ toResInstanceUid, componentId, relationPair.getCapability(), relationPair.getRelation().getCapabilityOwnerId(),
+ relationPair.getRelation().getRequirementOwnerId());
return Either.right(StorageOperationStatus.NOT_FOUND);
}
}
@@ -1644,14 +1772,13 @@ public class NodeTemplateOperation extends BaseOperation {
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
-
// update jsons
+
// update metadata of container and composition json
status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
-
return Either.left(requirementDef);
}
@@ -1664,16 +1791,15 @@ public class NodeTemplateOperation extends BaseOperation {
* @param predicate
* @return
*/
- public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation,
+ public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId,
+ RequirementCapabilityRelDef foundRelation,
BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
-
Either<RequirementDataDefinition, StorageOperationStatus> result = null;
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = null;
MapListRequirementDataDefinition reqMapOfLists = null;
Optional<RequirementDataDefinition> foundRequirement;
RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
- Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
JanusGraphOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error);
@@ -1695,7 +1821,8 @@ public class NodeTemplateOperation extends BaseOperation {
}
if (result == null && reqMapOfLists != null) {
for (ListRequirementDataDefinition requirements : reqMapOfLists.getMapToscaDataDefinition().values()) {
- foundRequirement = requirements.getListToscaDataDefinition().stream().filter(req -> predicate.test(relationshipInfo, req)).findFirst();
+ foundRequirement = requirements.getListToscaDataDefinition().stream().filter(req -> predicate.test(relationshipInfo, req))
+ .findFirst();
if (foundRequirement.isPresent()) {
result = Either.left(foundRequirement.get());
}
@@ -1713,17 +1840,15 @@ public class NodeTemplateOperation extends BaseOperation {
* @param predicate
* @return
*/
- public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation,
+ public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId,
+ RequirementCapabilityRelDef foundRelation,
BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
-
Either<CapabilityDataDefinition, StorageOperationStatus> result = null;
Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = null;
MapListCapabilityDataDefinition capMapOfLists = null;
Optional<CapabilityDataDefinition> foundRequirement;
-
RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
- Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
JanusGraphOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error);
@@ -1745,7 +1870,8 @@ public class NodeTemplateOperation extends BaseOperation {
}
if (result == null && capMapOfLists != null) {
for (ListCapabilityDataDefinition capabilities : capMapOfLists.getMapToscaDataDefinition().values()) {
- foundRequirement = capabilities.getListToscaDataDefinition().stream().filter(cap -> predicate.test(relationshipInfo, cap)).findFirst();
+ foundRequirement = capabilities.getListToscaDataDefinition().stream().filter(cap -> predicate.test(relationshipInfo, cap))
+ .findFirst();
if (foundRequirement.isPresent()) {
result = Either.left(foundRequirement.get());
}
@@ -1754,22 +1880,23 @@ public class NodeTemplateOperation extends BaseOperation {
return result;
}
- private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid,
- RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) {
+ private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(
+ Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement,
+ String fromResInstanceUid, RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) {
StorageOperationStatus status;
String hereIsTheKey = null;
MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid);
if (reqByInstance == null || reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()) == null) {
// move from fulfilled
- status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship);
+ status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey,
+ relationship);
} else {
hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId());
ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey);
- Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream()
- .filter(req -> req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())).findFirst();
-
+ Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream().filter(
+ req -> req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req
+ .getUniqueId().equals(relation.getRequirementId())).findFirst();
if (requirementOptional.isPresent()) {
-
RequirementDataDefinition requirement = requirementOptional.get();
String leftOccurrences = requirement.getLeftOccurrences();
if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
@@ -1783,14 +1910,17 @@ public class NodeTemplateOperation extends BaseOperation {
status = StorageOperationStatus.OK;
} else {
// move from fulfilled
- status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship);
+ status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey,
+ relationship);
}
}
return status;
}
- private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabilityDataDefinition> calculatedCapability, Map<String, MapListCapabilityDataDefinition> fullFilledCapability, String toResInstanceUid,
- RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) {
+ private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabilityDataDefinition> calculatedCapability,
+ Map<String, MapListCapabilityDataDefinition> fullFilledCapability,
+ String toResInstanceUid, RelationshipInstDataDefinition relation,
+ CapabilityRequirementRelationship relationship) {
StorageOperationStatus status;
String hereIsTheKey = null;
MapListCapabilityDataDefinition capByInstance = calculatedCapability.get(toResInstanceUid);
@@ -1800,11 +1930,10 @@ public class NodeTemplateOperation extends BaseOperation {
} else {
hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId());
ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey);
- Optional<CapabilityDataDefinition> capabilityOptional = capByType.getListToscaDataDefinition().stream().filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId()))
- .findFirst();
-
+ Optional<CapabilityDataDefinition> capabilityOptional = capByType.getListToscaDataDefinition().stream()
+ .filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId()))
+ .findFirst();
if (capabilityOptional.isPresent()) {
-
CapabilityDataDefinition capability = capabilityOptional.get();
String leftOccurrences = capability.getLeftOccurrences();
if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
@@ -1818,23 +1947,29 @@ public class NodeTemplateOperation extends BaseOperation {
status = StorageOperationStatus.OK;
} else {
// move from fulfilled
- status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey, relationship);
+ status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey,
+ relationship);
}
}
return status;
}
- private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabilityDataDefinition> calculatedCapability, Map<String, MapListCapabilityDataDefinition> fullFilledCapability, String toResInstanceUid,
- RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) {
+ private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabilityDataDefinition> calculatedCapability,
+ Map<String, MapListCapabilityDataDefinition> fullFilledCapability,
+ String toResInstanceUid, RelationshipInstDataDefinition relation, String hereIsTheKey,
+ CapabilityRequirementRelationship relationship) {
MapListCapabilityDataDefinition capByInstance = fullFilledCapability.get(toResInstanceUid);
if (capByInstance == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability in fulfilled list for instance {} ", toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
- if (null == hereIsTheKey)
+ if (null == hereIsTheKey) {
hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId());
+ }
if (null == hereIsTheKey) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability with id {} in fulfilled list for instance {} ", relation.getCapabilityId(), toResInstanceUid);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "No capability with id {} in fulfilled list for instance {} ", relation.getCapabilityId(),
+ toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey);
@@ -1850,7 +1985,6 @@ public class NodeTemplateOperation extends BaseOperation {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
++leftIntValue;
cap.setLeftOccurrences(String.valueOf(leftIntValue));
-
MapListCapabilityDataDefinition mapListCapaDataDef = calculatedCapability.get(toResInstanceUid);
if (mapListCapaDataDef == null) {
mapListCapaDataDef = new MapListCapabilityDataDefinition();
@@ -1861,29 +1995,37 @@ public class NodeTemplateOperation extends BaseOperation {
mapListCapaDataDef.put(hereIsTheKey, findByKey);
}
findByKey.add(cap);
- if (relationship != null)
+ if (relationship != null) {
relationship.setCapability(cap);
+ }
break;
}
}
if (!found) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getCapabilityOwnerId(), toResInstanceUid);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "No capability type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey,
+ relation.getCapabilityOwnerId(), toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
return StorageOperationStatus.OK;
}
- private StorageOperationStatus moveFromFullFilledRequirement(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid,
- RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) {
+ private StorageOperationStatus moveFromFullFilledRequirement(Map<String, MapListRequirementDataDefinition> calculatedRequirement,
+ Map<String, MapListRequirementDataDefinition> fullFilledRequirement,
+ String fromResInstanceUid, RelationshipInstDataDefinition relation,
+ String hereIsTheKey, CapabilityRequirementRelationship relationship) {
MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid);
if (reqByInstance == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
- if (null == hereIsTheKey)
+ if (null == hereIsTheKey) {
hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId());
+ }
if (null == hereIsTheKey) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement with id {} in fulfilled list for instance {} ", relation.getRequirementId(), fromResInstanceUid);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement with id {} in fulfilled list for instance {} ", relation.getRequirementId(),
+ fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey);
@@ -1891,7 +2033,8 @@ public class NodeTemplateOperation extends BaseOperation {
boolean found = false;
while (iterator.hasNext()) {
RequirementDataDefinition req = iterator.next();
- if (req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())) {
+ if (req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId()
+ .equals(relation.getRequirementId())) {
found = true;
iterator.remove();
// return to calculated list
@@ -1899,7 +2042,6 @@ public class NodeTemplateOperation extends BaseOperation {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
++leftIntValue;
req.setLeftOccurrences(String.valueOf(leftIntValue));
-
MapListRequirementDataDefinition mapListReqDataDef = calculatedRequirement.get(fromResInstanceUid);
if (mapListReqDataDef == null) {
mapListReqDataDef = new MapListRequirementDataDefinition();
@@ -1910,40 +2052,43 @@ public class NodeTemplateOperation extends BaseOperation {
mapListReqDataDef.put(hereIsTheKey, findByKey);
}
findByKey.add(req);
- if (relationship != null)
+ if (relationship != null) {
relationship.setRequirement(req);
+ }
break;
}
}
if (!found) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getRequirementOwnerId(), fromResInstanceUid);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey,
+ relation.getRequirementOwnerId(), fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
return StorageOperationStatus.OK;
-
}
public StorageOperationStatus updateCustomizationUUID(String componentInstanceId, CompositionDataDefinition compositionDataDefinition) {
ComponentInstanceDataDefinition componentInstance = compositionDataDefinition.getComponentInstances().get(componentInstanceId);
-
if (componentInstance == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component instance by id {} from map of instances ", componentInstanceId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component instance by id {} from map of instances ", componentInstanceId);
return StorageOperationStatus.NOT_FOUND;
}
UUID uuid = UUID.randomUUID();
componentInstance.setCustomizationUUID(uuid.toString());
-
return StorageOperationStatus.OK;
}
- public <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectInstancesInContainer(String fromResInstanceUid, String toResInstanceUid, RelationshipInfo relationPair, boolean originUI,
- Map<String, MapListCapabilityDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty,
- Map<String, MapListRequirementDataDefinition> fullfilledRequirement, CompositionDataDefinition compositionDataDefinition, String containerId) {
+ public <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectInstancesInContainer(
+ String fromResInstanceUid, String toResInstanceUid, RelationshipInfo relationPair, boolean originUI,
+ Map<String, MapListCapabilityDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement,
+ Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty, Map<String, MapListRequirementDataDefinition> fullfilledRequirement,
+ CompositionDataDefinition compositionDataDefinition, String containerId) {
String requirement = relationPair.getRequirement();
Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances();
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, containerId, requirement);
-
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid,
+ toResInstanceUid, containerId, requirement);
ComponentInstanceDataDefinition fromResourceInstData = componentInstances.get(fromResInstanceUid);
if (fromResourceInstData == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find from resource instance {}.", fromResInstanceUid);
@@ -1954,39 +2099,46 @@ public class NodeTemplateOperation extends BaseOperation {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find to resource instance {}.", toResInstanceUid);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
-
- Either<Map<JsonPresentationFields, T>, StorageOperationStatus> reqVsCap = connectRequirementVsCapability(fromResourceInstData, toResourceInstData, relationPair, originUI, calculatedCapabilty, calculatedRequirement, fullfilledCapabilty,
- fullfilledRequirement, containerId);
+ Either<Map<JsonPresentationFields, T>, StorageOperationStatus> reqVsCap = connectRequirementVsCapability(fromResourceInstData,
+ toResourceInstData, relationPair, originUI, calculatedCapabilty, calculatedRequirement, fullfilledCapabilty, fullfilledRequirement,
+ containerId);
if (reqVsCap.isRight()) {
StorageOperationStatus status = reqVsCap.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to connect requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to connect requirement {} between resource instance {} to resource instance {}. status is {}", requirement,
+ fromResInstanceUid, toResInstanceUid, status);
return Either.right(status);
}
Map<JsonPresentationFields, T> relationship = reqVsCap.left().value();
-
// add to json new relations
- compositionDataDefinition.addRelation(((RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP)).getUniqueId(), (RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP));
-
+ compositionDataDefinition.addRelation(((RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP)).getUniqueId(),
+ (RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP));
return Either.left(relationship);
}
- private Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedCapability(GraphVertex containerV, EdgeLabelEnum capLabel) {
-
- Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, JanusGraphOperationStatus> calculatedCapabiltyEither = getDataAndVertexFromGraph(containerV, capLabel);
+ private Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedCapability(
+ GraphVertex containerV, EdgeLabelEnum capLabel) {
+ Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, JanusGraphOperationStatus> calculatedCapabiltyEither = getDataAndVertexFromGraph(
+ containerV, capLabel);
if (calculatedCapabiltyEither.isRight()) {
JanusGraphOperationStatus error = calculatedCapabiltyEither.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilties for container {}.", containerV.getUniqueId(), error);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilties for container {}.", containerV.getUniqueId(), error);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>> calculatedCapabilty = calculatedCapabiltyEither.left().value();
return Either.left(calculatedCapabilty);
}
- private Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedRequirement(GraphVertex containerV, EdgeLabelEnum reqLabel) {
- Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, JanusGraphOperationStatus> calculatedRequirementEither = getDataAndVertexFromGraph(containerV, reqLabel);
+ private Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedRequirement(
+ GraphVertex containerV, EdgeLabelEnum reqLabel) {
+ Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, JanusGraphOperationStatus> calculatedRequirementEither = getDataAndVertexFromGraph(
+ containerV, reqLabel);
if (calculatedRequirementEither.isRight()) {
JanusGraphOperationStatus error = calculatedRequirementEither.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for container {}.", containerV.getUniqueId(), error);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for container {}.", containerV.getUniqueId(),
+ error);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>> calculatedRequirement = calculatedRequirementEither.left().value();
@@ -1994,23 +2146,27 @@ public class NodeTemplateOperation extends BaseOperation {
}
@SuppressWarnings("unchecked")
- private <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectRequirementVsCapability(ComponentInstanceDataDefinition fromResInstance, ComponentInstanceDataDefinition toResInstance,
- RelationshipInfo relationPair, boolean originUI, Map<String, MapListCapabilityDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement,
- Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty, Map<String, MapListRequirementDataDefinition> fullfilledRequirement, String containerId) {
+ private <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectRequirementVsCapability(
+ ComponentInstanceDataDefinition fromResInstance, ComponentInstanceDataDefinition toResInstance, RelationshipInfo relationPair,
+ boolean originUI, Map<String, MapListCapabilityDataDefinition> calculatedCapabilty,
+ Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty,
+ Map<String, MapListRequirementDataDefinition> fullfilledRequirement, String containerId) {
String type = relationPair.getRelationship().getType();
// capability
-
String toInstId = toResInstance.getUniqueId();
MapListCapabilityDataDefinition mapListCapabilityDataDefinition = calculatedCapabilty.get(toInstId);
Map<JsonPresentationFields, T> capReqRelationship = new EnumMap<>(JsonPresentationFields.class);
-
if (mapListCapabilityDataDefinition == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for instance {} in container {}.", toInstId, containerId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for instance {} in container {}.", toInstId,
+ containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
ListCapabilityDataDefinition listCapabilityDataDefinition = mapListCapabilityDataDefinition.getMapToscaDataDefinition().get(type);
if (listCapabilityDataDefinition == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type, toInstId, containerId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type,
+ toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
CapabilityDataDefinition capabilityForRelation = null;
@@ -2035,7 +2191,6 @@ public class NodeTemplateOperation extends BaseOperation {
mapListCapabiltyFullFilledInst = new MapListCapabilityDataDefinition();
fullfilledCapabilty.put(toInstId, mapListCapabiltyFullFilledInst);
}
-
ListCapabilityDataDefinition listCapabilityFull = mapListCapabiltyFullFilledInst.findByKey(type);
if (listCapabilityFull == null) {
listCapabilityFull = new ListCapabilityDataDefinition();
@@ -2045,30 +2200,35 @@ public class NodeTemplateOperation extends BaseOperation {
}
break;
} else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabilityForRelation.getType(), toInstId, containerId);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.",
+ capabilityForRelation.getType(), toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
}
}
}
if (capabilityForRelation == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch capabilty for type {} for instance {} in container {}.", type, toInstId, containerId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch capabilty for type {} for instance {} in container {}.", type, toInstId,
+ containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
-
// requirements
String fromInstId = fromResInstance.getUniqueId();
MapListRequirementDataDefinition mapListRequirementDataDefinition = calculatedRequirement.get(fromInstId);
if (mapListRequirementDataDefinition == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for instance {} in container {}.", fromInstId, containerId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for instance {} in container {}.", fromInstId,
+ containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
ListRequirementDataDefinition listRequirementDataDefinition = mapListRequirementDataDefinition.getMapToscaDataDefinition().get(type);
if (listRequirementDataDefinition == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for type {} for instance {} in container {}.", type, fromInstId, containerId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for type {} for instance {} in container {}.", type,
+ fromInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
-
RequirementDataDefinition requirementForRelation = null;
Iterator<RequirementDataDefinition> iteratorReq = listRequirementDataDefinition.getListToscaDataDefinition().iterator();
while (iteratorReq.hasNext()) {
@@ -2091,7 +2251,6 @@ public class NodeTemplateOperation extends BaseOperation {
mapListRequirementFullFilledInst = new MapListRequirementDataDefinition();
fullfilledRequirement.put(fromInstId, mapListRequirementFullFilledInst);
}
-
ListRequirementDataDefinition listRequirementFull = mapListRequirementFullFilledInst.findByKey(type);
if (listRequirementFull == null) {
listRequirementFull = new ListRequirementDataDefinition();
@@ -2101,34 +2260,37 @@ public class NodeTemplateOperation extends BaseOperation {
}
break;
} else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No left occurrences requirement {} from {} to {} in container {}.", requirementForRelation.getCapability(), fromInstId, toInstId, containerId);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No left occurrences requirement {} from {} to {} in container {}.",
+ requirementForRelation.getCapability(), fromInstId, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
}
}
}
if (requirementForRelation == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch requirement for type {} for instance {} in container {}.", type, toInstId, containerId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch requirement for type {} for instance {} in container {}.", type, toInstId,
+ containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
if (!capabilityForRelation.getType().equals(requirementForRelation.getCapability())) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No macth for capability from type {} and requirement {} from {} to {} in container {}.", capabilityForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId,
- containerId);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "No macth for capability from type {} and requirement {} from {} to {} in container {}.",
+ capabilityForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
-
RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair, originUI);
- if (requirementForRelation.getRelationship() != null)
+ if (requirementForRelation.getRelationship() != null) {
relationshipTypeData.setType(requirementForRelation.getRelationship());
+ }
capReqRelationship.put(JsonPresentationFields.RELATIONSHIP, (T) relationshipTypeData);
return Either.left(capReqRelationship);
}
- private RelationshipInstDataDefinition buildRelationshipInstData(String fromResInstanceUid, String toInstId, RelationshipInfo relationPair, boolean originUI) {
-
+ private RelationshipInstDataDefinition buildRelationshipInstData(String fromResInstanceUid, String toInstId, RelationshipInfo relationPair,
+ boolean originUI) {
RelationshipInstDataDefinition relationshipInstData = new RelationshipInstDataDefinition();
relationshipInstData.setUniqueId(UniqueIdBuilder.buildRelationsipInstInstanceUid(fromResInstanceUid, toInstId));
-
relationshipInstData.setType(relationPair.getRelationship().getType());
Long creationDate = System.currentTimeMillis();
relationshipInstData.setCreationTime(creationDate);
@@ -2142,12 +2304,14 @@ public class NodeTemplateOperation extends BaseOperation {
relationshipInstData.setRequirement(relationPair.getRequirement());
relationshipInstData.setCapability(relationPair.getCapability());
relationshipInstData.setOriginUI(originUI);
-
return relationshipInstData;
}
- public <T extends Component> Map<String, ComponentInstanceDataDefinition> associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, T> componentInstanceTMap, GraphVertex containerVertex, boolean allowDeleted, boolean isUpdateCsar) {
-
+ public <T extends Component> Map<String, ComponentInstanceDataDefinition> associateComponentInstancesToComponent(Component containerComponent,
+ Map<ComponentInstance, T> componentInstanceTMap,
+ GraphVertex containerVertex,
+ boolean allowDeleted,
+ boolean isUpdateCsar) {
String containerId = containerComponent.getUniqueId();
Map<String, ComponentInstanceDataDefinition> instancesJsonData;
Either<GraphVertex, JanusGraphOperationStatus> updateElement = null;
@@ -2158,7 +2322,6 @@ public class NodeTemplateOperation extends BaseOperation {
throw new StorageException(StorageOperationStatus.INCONSISTENCY);
}
instancesJsonData = convertToComponentInstanceDataDefinition(componentInstanceTMap, containerId, isUpdateCsar);
-
if (MapUtils.isNotEmpty(instancesJsonData)) {
containerVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
Map<String, CompositionDataDefinition> compositions = new HashMap<>();
@@ -2168,7 +2331,8 @@ public class NodeTemplateOperation extends BaseOperation {
containerVertex.setJson(compositions);
updateElement = janusGraphDao.updateVertex(containerVertex);
if (updateElement.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instances. ", containerComponent.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instances. ",
+ containerComponent.getName());
throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
}
}
@@ -2179,11 +2343,12 @@ public class NodeTemplateOperation extends BaseOperation {
return instancesJsonData;
}
- private <T extends Component> Map<String, ComponentInstanceDataDefinition> convertToComponentInstanceDataDefinition(Map<ComponentInstance, T> componentInstanceTMap, String containerId, boolean isUpdateCsar) {
-
+ private <T extends Component> Map<String, ComponentInstanceDataDefinition> convertToComponentInstanceDataDefinition(
+ Map<ComponentInstance, T> componentInstanceTMap, String containerId, boolean isUpdateCsar) {
Map<String, ComponentInstanceDataDefinition> instances = new HashMap<>();
for (Entry<ComponentInstance, T> entry : componentInstanceTMap.entrySet()) {
- ComponentInstanceDataDefinition instance = buildComponentInstanceDataDefinition(entry.getKey(), containerId, null, !isUpdateCsar || entry.getKey().isCreatedFromCsar(), ModelConverter.convertToToscaElement(entry.getValue()));
+ ComponentInstanceDataDefinition instance = buildComponentInstanceDataDefinition(entry.getKey(), containerId, null,
+ !isUpdateCsar || entry.getKey().isCreatedFromCsar(), ModelConverter.convertToToscaElement(entry.getValue()));
instances.put(instance.getUniqueId(), instance);
}
return instances;
@@ -2193,7 +2358,8 @@ public class NodeTemplateOperation extends BaseOperation {
boolean result = true;
for (Component component : resourcesInstancesMap.values()) {
if (component.getIsDeleted() != null && component.getIsDeleted()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance. ", component.getName());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance. ", component.getName());
result = false;
break;
}
@@ -2206,14 +2372,14 @@ public class NodeTemplateOperation extends BaseOperation {
Set<String> names = new HashSet<>();
for (ComponentInstance instance : resourcesInstancesMap.keySet()) {
if (StringUtils.isEmpty(instance.getName())) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
- "Component instance {} name is empty. Cannot add component instance. ", instance.getUniqueId());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component instance {} name is empty. Cannot add component instance. ",
+ instance.getUniqueId());
result = false;
break;
} else if (names.contains(instance.getName())) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
- "Component instance with the name {} already exsists. Cannot add component instance. ",
- instance.getName());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Component instance with the name {} already exsists. Cannot add component instance. ",
+ instance.getName());
result = false;
break;
} else {
@@ -2223,17 +2389,22 @@ public class NodeTemplateOperation extends BaseOperation {
return result;
}
- public StorageOperationStatus addDeploymentArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts) {
- return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS);
+ public StorageOperationStatus addDeploymentArtifactsToInstance(String toscaElementId, String instanceId,
+ Map<String, ArtifactDataDefinition> instDeplArtifacts) {
+ return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS,
+ VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS);
}
- public StorageOperationStatus addInformationalArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts) {
- return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS);
+ public StorageOperationStatus addInformationalArtifactsToInstance(String toscaElementId, String instanceId,
+ Map<String, ArtifactDataDefinition> instDeplArtifacts) {
+ return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INSTANCE_ARTIFACTS,
+ VertexTypeEnum.INSTANCE_ARTIFACTS);
}
- public StorageOperationStatus addArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexType) {
- Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
- .getVertexById(toscaElementId, JsonParseFlagEnum.NoParse);
+ public StorageOperationStatus addArtifactsToInstance(String toscaElementId, String instanceId,
+ Map<String, ArtifactDataDefinition> instDeplArtifacts, EdgeLabelEnum edgeLabel,
+ VertexTypeEnum vertexType) {
+ Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse);
if (metadataVertex.isRight()) {
JanusGraphOperationStatus status = metadataVertex.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -2243,13 +2414,11 @@ public class NodeTemplateOperation extends BaseOperation {
}
MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeplArtifacts);
return addToscaDataDeepElementsBlockToToscaElement(metadataVertex.left().value(), edgeLabel, vertexType, instArtifacts, instanceId);
-
}
@SuppressWarnings({"unchecked"})
public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
- Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (metadataVertex.isRight()) {
JanusGraphOperationStatus status = metadataVertex.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -2275,7 +2444,8 @@ public class NodeTemplateOperation extends BaseOperation {
public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
if (groupInstances != null) {
- Either<Map<String, MapGroupsDataDefinition>, JanusGraphOperationStatus> dataFromGraph = getDataFromGraph(componentId, EdgeLabelEnum.INST_GROUPS);
+ Either<Map<String, MapGroupsDataDefinition>, JanusGraphOperationStatus> dataFromGraph = getDataFromGraph(componentId,
+ EdgeLabelEnum.INST_GROUPS);
if (dataFromGraph.isRight()) {
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(dataFromGraph.right().value());
}
@@ -2293,42 +2463,47 @@ public class NodeTemplateOperation extends BaseOperation {
UUID uuid = UUID.randomUUID();
groupInst.setCustomizationUUID(uuid.toString());
}
-
}
return StorageOperationStatus.OK;
}
- public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
-
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
+ List<GroupInstance> groupInstances) {
return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS,
- new MapDataDefinition<>(groupInstances.stream().collect(Collectors.toMap(GroupInstanceDataDefinition::getName, gi -> gi))), componentInstance.getUniqueId());
+ new MapDataDefinition<>(groupInstances.stream().collect(Collectors.toMap(GroupInstanceDataDefinition::getName, gi -> gi))),
+ componentInstance.getUniqueId());
}
- public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
-
- return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, new MapDataDefinition<>(deploymentArtifacts),
- componentInstance.getUniqueId());
+ public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
+ Map<String, ArtifactDefinition> deploymentArtifacts) {
+ return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS,
+ VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, new MapDataDefinition<>(deploymentArtifacts), componentInstance.getUniqueId());
}
- public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
-
+ public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId,
+ ComponentInstanceProperty property) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
- return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME);
+ return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES,
+ VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME);
}
- public StorageOperationStatus updateComponentInstanceCapabilityProperty(Component containerComponent, String componentInstanceId, String capabilityPropertyKey, ComponentInstanceProperty property) {
+ public StorageOperationStatus updateComponentInstanceCapabilityProperty(Component containerComponent, String componentInstanceId,
+ String capabilityPropertyKey, ComponentInstanceProperty property) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
pathKeys.add(capabilityPropertyKey);
- return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME);
+ return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
+ VertexTypeEnum.CALCULATED_CAP_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME);
}
- public StorageOperationStatus overrideComponentCapabilitiesProperties(Component containerComponent, Map<String, MapCapabilityProperty> capabilityPropertyMap) {
+ public StorageOperationStatus overrideComponentCapabilitiesProperties(Component containerComponent,
+ Map<String, MapCapabilityProperty> capabilityPropertyMap) {
return overrideToscaDataOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilityPropertyMap);
}
- public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
+ public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId,
+ ComponentInstanceProperty property) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES,
@@ -2343,16 +2518,14 @@ public class NodeTemplateOperation extends BaseOperation {
VertexTypeEnum.INST_PROPERTIES, properties, pathKeys, JsonPresentationFields.NAME);
}
- public StorageOperationStatus updateComponentInstanceAttributes(final Component containerComponent,
- final String componentInstanceId,
+ public StorageOperationStatus updateComponentInstanceAttributes(final Component containerComponent, final String componentInstanceId,
final List<ComponentInstanceAttribute> attributes) {
final List<String> pathKeys = Arrays.asList(componentInstanceId);
return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_ATTRIBUTES,
VertexTypeEnum.INST_ATTRIBUTES, attributes, pathKeys, JsonPresentationFields.NAME);
}
- public StorageOperationStatus updateComponentInstanceAttribute(final Component containerComponent,
- final String componentInstanceId,
+ public StorageOperationStatus updateComponentInstanceAttribute(final Component containerComponent, final String componentInstanceId,
final ComponentInstanceAttribute attribute) {
final List<String> pathKeys = Arrays.asList(componentInstanceId);
return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_ATTRIBUTES,
@@ -2371,50 +2544,60 @@ public class NodeTemplateOperation extends BaseOperation {
ComponentInstanceInput property) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
- return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME);
+ return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS,
+ property, pathKeys, JsonPresentationFields.NAME);
}
- public StorageOperationStatus updateComponentInstanceOutput(Component containerComponent, String componentInstanceId, ComponentInstanceOutput property) {
+ public StorageOperationStatus updateComponentInstanceOutput(Component containerComponent, String componentInstanceId,
+ ComponentInstanceOutput property) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
- return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_OUTPUTS, VertexTypeEnum.INST_OUTPUTS, property, pathKeys, JsonPresentationFields.NAME);
+ return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_OUTPUTS, VertexTypeEnum.INST_OUTPUTS,
+ property, pathKeys, JsonPresentationFields.NAME);
}
- public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> properties) {
+ public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId,
+ List<ComponentInstanceInput> properties) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
- return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, properties, pathKeys, JsonPresentationFields.NAME);
+ return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS,
+ properties, pathKeys, JsonPresentationFields.NAME);
}
- public StorageOperationStatus updateComponentInstanceOutputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceOutput> properties) {
+ public StorageOperationStatus updateComponentInstanceOutputs(Component containerComponent, String componentInstanceId,
+ List<ComponentInstanceOutput> properties) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
- return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_OUTPUTS, VertexTypeEnum.INST_OUTPUTS, properties, pathKeys, JsonPresentationFields.NAME);
+ return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_OUTPUTS, VertexTypeEnum.INST_OUTPUTS,
+ properties, pathKeys, JsonPresentationFields.NAME);
}
- public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
+ public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId,
+ ComponentInstanceInput property) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
- return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME);
+ return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS,
+ property, pathKeys, JsonPresentationFields.NAME);
}
- public StorageOperationStatus addComponentInstanceOutput(Component containerComponent, String componentInstanceId, ComponentInstanceOutput property) {
- List<String> pathKeys = new ArrayList<>(){};
+ public StorageOperationStatus addComponentInstanceOutput(Component containerComponent, String componentInstanceId,
+ ComponentInstanceOutput property) {
+ List<String> pathKeys = new ArrayList<>() {
+ };
pathKeys.add(componentInstanceId);
- return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_OUTPUTS, VertexTypeEnum.INST_OUTPUTS, property, pathKeys, JsonPresentationFields.NAME);
+ return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_OUTPUTS, VertexTypeEnum.INST_OUTPUTS,
+ property, pathKeys, JsonPresentationFields.NAME);
}
public StorageOperationStatus createInstanceEdge(GraphVertex metadataVertex, ComponentInstanceDataDefinition componentInstance) {
String instUniqueId = componentInstance.getUniqueId();
-
// create edge between container and origin ( in case of proxy this edge will be to ProxyService node type)
- StorageOperationStatus result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(), instUniqueId).either(v -> StorageOperationStatus.OK,
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
-
+ StorageOperationStatus result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(),
+ instUniqueId).either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (result == StorageOperationStatus.OK && componentInstance.getIsProxy()) {
// create edge between container and service origin
result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId)
- .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
return result;
}
@@ -2426,16 +2609,13 @@ public class NodeTemplateOperation extends BaseOperation {
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexById.right().value());
}
GraphVertex metadataVertex = vertexById.left().value();
-
EnumMap<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
props.put(GraphPropertyEnum.UUID, serviceUUID);
props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
EnumMap<GraphPropertyEnum, Object> hasNot = new EnumMap<>(GraphPropertyEnum.class);
hasNot.put(GraphPropertyEnum.IS_DELETED, true);
-
Either<List<GraphVertex>, JanusGraphOperationStatus> byCriteria = janusGraphDao
- .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props,hasNot, JsonParseFlagEnum.ParseMetadata );
+ .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props, hasNot, JsonParseFlagEnum.ParseMetadata);
if (byCriteria.isRight()) {
log.debug("Failed to fetch vertex by criteria {} error {}", props, byCriteria.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(byCriteria.right().value());
@@ -2445,49 +2625,43 @@ public class NodeTemplateOperation extends BaseOperation {
if (vertecies != null) {
GraphVertex serviceVertex = vertecies.get(0);
//remove previous edges
-
log.debug("Try to create or update edge between resource {} and service {} ", metadataVertex, serviceVertex.getUniqueId());
// create edge between container and service reference
- result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.ALLOTTED_OF, serviceVertex.getUniqueId(), instanceId).either(v -> StorageOperationStatus.OK,
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.ALLOTTED_OF, serviceVertex.getUniqueId(), instanceId)
+ .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
return result;
}
-
public StorageOperationStatus removeInstanceEdge(GraphVertex metadataVertex, ComponentInstanceDataDefinition componentInstance) {
String instUniqueId = componentInstance.getUniqueId();
-
// create edge between container and origin ( in case of proxy this edge will be to ProxyService node type)
- StorageOperationStatus result = removeOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(), instUniqueId)
- .either(v -> StorageOperationStatus.OK,
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
-
+ StorageOperationStatus result = removeOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(),
+ instUniqueId).either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (componentInstance.getIsProxy()) {
// create edge between container and service origin
result = removeOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId)
- .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
return result;
}
- private Either<GraphVertex, JanusGraphOperationStatus> createOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId) {
+ private Either<GraphVertex, JanusGraphOperationStatus> createOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel,
+ String componentUid, String instUniqueId) {
Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
properties.put(GraphPropertyEnum.UNIQUE_ID, componentUid);
-
- return janusGraphDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties)
- .left()
- .bind(v -> addInstanceToPropertyOnEdge(instUniqueId, v, metadataVertex))
- .right()
- .bind(s -> createInstanceEdge(metadataVertex, edgeLabel, componentUid, instUniqueId, s));
+ return janusGraphDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties).left()
+ .bind(v -> addInstanceToPropertyOnEdge(instUniqueId, v, metadataVertex)).right()
+ .bind(s -> createInstanceEdge(metadataVertex, edgeLabel, componentUid, instUniqueId, s));
}
- private Either<GraphVertex, JanusGraphOperationStatus> removeOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId) {
+ private Either<GraphVertex, JanusGraphOperationStatus> removeOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel,
+ String componentUid, String instUniqueId) {
Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
properties.put(GraphPropertyEnum.UNIQUE_ID, componentUid);
-
- return janusGraphDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties).left().bind(v -> removeInstanceFromPropertyOnEdge(instUniqueId, v, metadataVertex)).right()
- .map(err -> removeInstanceEdgeLogError(metadataVertex, edgeLabel, componentUid, err));
+ return janusGraphDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties).left()
+ .bind(v -> removeInstanceFromPropertyOnEdge(instUniqueId, v, metadataVertex)).right()
+ .map(err -> removeInstanceEdgeLogError(metadataVertex, edgeLabel, componentUid, err));
}
private Either<GraphVertex, JanusGraphOperationStatus> addInstanceToPropertyOnEdge(String instUniqueId, Edge edge, GraphVertex metadataVertex) {
@@ -2506,12 +2680,13 @@ public class NodeTemplateOperation extends BaseOperation {
edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr);
} catch (IOException e) {
log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e);
- return Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
+ return Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
}
return Either.left(metadataVertex);
}
- private Either<GraphVertex, JanusGraphOperationStatus> removeInstanceFromPropertyOnEdge(String instUniqueId, Edge edge, GraphVertex metadataVertex) {
+ private Either<GraphVertex, JanusGraphOperationStatus> removeInstanceFromPropertyOnEdge(String instUniqueId, Edge edge,
+ GraphVertex metadataVertex) {
// edge exist need to add instance id to list on edge's property
List<String> property = (List<String>) janusGraphDao.getProperty(edge, EdgePropertyEnum.INSTANCES);
if (property == null) {
@@ -2530,13 +2705,15 @@ public class NodeTemplateOperation extends BaseOperation {
edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr);
} catch (IOException e) {
log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e);
- return Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
+ return Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
}
}
return Either.left(metadataVertex);
}
- private Either<GraphVertex, JanusGraphOperationStatus> createInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId, JanusGraphOperationStatus retrieveEdgeStatus) {
+ private Either<GraphVertex, JanusGraphOperationStatus> createInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel,
+ String componentUid, String instUniqueId,
+ JanusGraphOperationStatus retrieveEdgeStatus) {
if (retrieveEdgeStatus == JanusGraphOperationStatus.NOT_FOUND) {
// create new edge
Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentUid);
@@ -2548,11 +2725,9 @@ public class NodeTemplateOperation extends BaseOperation {
List<String> instList = new ArrayList<>();
instList.add(instUniqueId);
edgeProps.put(EdgePropertyEnum.INSTANCES, instList);
-
- log.debug("Create new edge {} between {} and {} and properties {} ", edgeLabel, metadataVertex.getUniqueId(), originVertex.getUniqueId(), edgeProps);
- JanusGraphOperationStatus
- edgeResult = janusGraphDao
- .createEdge(metadataVertex, originVertex, edgeLabel, edgeProps);
+ log.debug("Create new edge {} between {} and {} and properties {} ", edgeLabel, metadataVertex.getUniqueId(), originVertex.getUniqueId(),
+ edgeProps);
+ JanusGraphOperationStatus edgeResult = janusGraphDao.createEdge(metadataVertex, originVertex, edgeLabel, edgeProps);
return edgeResult == JanusGraphOperationStatus.OK ? Either.left(metadataVertex) : Either.right(edgeResult);
}
// error
@@ -2560,7 +2735,8 @@ public class NodeTemplateOperation extends BaseOperation {
return Either.right(retrieveEdgeStatus);
}
- private JanusGraphOperationStatus removeInstanceEdgeLogError(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, JanusGraphOperationStatus retrieveEdgeStatus) {
+ private JanusGraphOperationStatus removeInstanceEdgeLogError(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid,
+ JanusGraphOperationStatus retrieveEdgeStatus) {
if (retrieveEdgeStatus == JanusGraphOperationStatus.NOT_FOUND) {
log.debug("No edge {} to remove between container {} and origin {}", edgeLabel, metadataVertex.getUniqueId(), componentUid);
} else {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java
index 10c58ba697..3369d65f76 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.jsonjanusgraph.operations;
+import com.vdurmont.semver4j.Semver;
+import com.vdurmont.semver4j.Semver.SemverType;
import fj.data.Either;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -63,32 +63,27 @@ import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
-import com.vdurmont.semver4j.Semver;
-import com.vdurmont.semver4j.Semver.SemverType;
@org.springframework.stereotype.Component("node-type-operation")
public class NodeTypeOperation extends ToscaElementOperation {
+
public static final Pattern uuidNewVersion = Pattern.compile("^\\d+.1");
public static final Pattern uuidNormativeNewVersion = Pattern.compile("^\\d+.0");
private static final Logger log = Logger.getLogger(NodeTypeOperation.class);
private DerivedNodeTypeResolver derivedResourceResolver;
-
public NodeTypeOperation(@Qualifier("derived-resource-resolver") DerivedNodeTypeResolver derivedNodeTypeResolver) {
this.derivedResourceResolver = derivedNodeTypeResolver;
}
public Either<NodeType, StorageOperationStatus> createNodeType(NodeType nodeType) {
-
nodeType.generateUUID();
-
nodeType = getResourceMetaDataFromResource(nodeType);
String resourceUniqueId = nodeType.getUniqueId();
if (resourceUniqueId == null) {
resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId();
nodeType.setUniqueId(resourceUniqueId);
}
-
// get derived from resources
List<GraphVertex> derivedResources = null;
Either<List<GraphVertex>, StorageOperationStatus> derivedResourcesResult = findDerivedResources(nodeType);
@@ -97,10 +92,8 @@ public class NodeTypeOperation extends ToscaElementOperation {
} else {
derivedResources = derivedResourcesResult.left().value();
}
-
GraphVertex nodeTypeVertex = new GraphVertex(VertexTypeEnum.NODE_TYPE);
fillToscaElementVertexData(nodeTypeVertex, nodeType, JsonParseFlagEnum.ParseAll);
-
Either<GraphVertex, JanusGraphOperationStatus> createdVertex = janusGraphDao.createVertex(nodeTypeVertex);
if (createdVertex.isRight()) {
JanusGraphOperationStatus status = createdVertex.right().value();
@@ -108,12 +101,10 @@ public class NodeTypeOperation extends ToscaElementOperation {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
nodeTypeVertex = createdVertex.left().value();
-
StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(nodeTypeVertex, nodeType, derivedResources);
if (assosiateCommon != StorageOperationStatus.OK) {
return Either.right(assosiateCommon);
}
-
StorageOperationStatus associateDerived = assosiateToDerived(nodeTypeVertex, derivedResources);
if (associateDerived != StorageOperationStatus.OK) {
return Either.right(associateDerived);
@@ -122,17 +113,14 @@ public class NodeTypeOperation extends ToscaElementOperation {
if (associateCategory != StorageOperationStatus.OK) {
return Either.right(associateCategory);
}
-
StorageOperationStatus associateAttributes = associateAttributesToResource(nodeTypeVertex, nodeType, derivedResources);
if (associateAttributes != StorageOperationStatus.OK) {
return Either.right(associateAttributes);
}
-
StorageOperationStatus associateRequirements = associateRequirementsToResource(nodeTypeVertex, nodeType, derivedResources);
if (associateRequirements != StorageOperationStatus.OK) {
return Either.right(associateRequirements);
}
-
StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(nodeTypeVertex, nodeType, derivedResources);
if (associateCapabilities != StorageOperationStatus.OK) {
return Either.right(associateCapabilities);
@@ -141,12 +129,10 @@ public class NodeTypeOperation extends ToscaElementOperation {
if (associateCapabilitiesProps != StorageOperationStatus.OK) {
return Either.right(associateCapabilitiesProps);
}
-
StorageOperationStatus associateInterfaces = associateInterfacesToResource(nodeTypeVertex, nodeType, derivedResources);
if (associateInterfaces != StorageOperationStatus.OK) {
return Either.right(associateInterfaces);
}
-
StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(nodeTypeVertex, nodeType, derivedResources);
if (addAdditionalInformation != StorageOperationStatus.OK) {
return Either.right(addAdditionalInformation);
@@ -156,18 +142,19 @@ public class NodeTypeOperation extends ToscaElementOperation {
private StorageOperationStatus associateInterfacesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
// Note : currently only one derived supported!!!!
- Either<Map<String, InterfaceDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.INTERFACE_ARTIFACTS);
+ Either<Map<String, InterfaceDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources,
+ EdgeLabelEnum.INTERFACE_ARTIFACTS);
if (dataFromDerived.isRight()) {
return dataFromDerived.right().value();
}
Map<String, InterfaceDataDefinition> interfacArtsAll = dataFromDerived.left().value();
-
Map<String, InterfaceDataDefinition> interfacArts = nodeType.getInterfaceArtifacts();
if (interfacArts != null) {
interfacArtsAll.putAll(interfacArts);
}
if (!interfacArtsAll.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INTERFACE_ARTIFACTS, EdgeLabelEnum.INTERFACE_ARTIFACTS, interfacArtsAll);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.INTERFACE_ARTIFACTS, EdgeLabelEnum.INTERFACE_ARTIFACTS, interfacArtsAll);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -177,15 +164,13 @@ public class NodeTypeOperation extends ToscaElementOperation {
@Override
public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) {
-
- Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
+ Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.NODE_TYPE,
+ JsonParseFlagEnum.ParseMetadata);
if (componentByLabelAndId.isRight()) {
return Either.right(componentByLabelAndId.right().value());
}
GraphVertex componentV = componentByLabelAndId.left().value();
-
return getToscaElement(componentV, componentParametersView);
-
}
// -------------------------------------------------------------
@@ -199,34 +184,29 @@ public class NodeTypeOperation extends ToscaElementOperation {
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
status = setLastModifierFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
-
if (!componentParametersView.isIgnoreProperties()) {
status = setResourcePropertiesFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK && status != JanusGraphOperationStatus.NOT_FOUND) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
-
if (!componentParametersView.isIgnoreAttributes()) {
status = setResourceAttributesFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
-
if (!componentParametersView.isIgnoreDerivedFrom()) {
status = setResourceDerivedFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
-
if (!componentParametersView.isIgnoreCategories()) {
status = setResourceCategoryFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
@@ -246,7 +226,6 @@ public class NodeTypeOperation extends ToscaElementOperation {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
-
if (!componentParametersView.isIgnoreArtifacts()) {
status = setArtifactsFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
@@ -271,19 +250,18 @@ public class NodeTypeOperation extends ToscaElementOperation {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
-
if (!componentParametersView.isIgnoreCapabiltyProperties()) {
status = setComponentCapPropertiesFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
-
}
}
return Either.left(toscaElement);
}
private JanusGraphOperationStatus setComponentCapPropertiesFromGraph(GraphVertex componentV, NodeType toscaElement) {
- Either<Map<String, MapPropertiesDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES_PROPERTIES);
+ Either<Map<String, MapPropertiesDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.CAPABILITIES_PROPERTIES);
if (result.isLeft()) {
toscaElement.setCapabilitiesProperties(result.left().value());
} else {
@@ -295,7 +273,8 @@ public class NodeTypeOperation extends ToscaElementOperation {
}
private JanusGraphOperationStatus setInterfacesFromGraph(GraphVertex componentV, NodeType toscaElement) {
- Either<Map<String, InterfaceDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INTERFACE_ARTIFACTS);
+ Either<Map<String, InterfaceDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.INTERFACE_ARTIFACTS);
if (result.isLeft()) {
toscaElement.setInterfaceArtifacts(result.left().value());
} else {
@@ -311,7 +290,8 @@ public class NodeTypeOperation extends ToscaElementOperation {
}
private JanusGraphOperationStatus setResourceCapabilitiesFromGraph(GraphVertex componentV, NodeType toscaElement) {
- Either<Map<String, ListCapabilityDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES);
+ Either<Map<String, ListCapabilityDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.CAPABILITIES);
if (result.isLeft()) {
toscaElement.setCapabilities(result.left().value());
} else {
@@ -322,17 +302,13 @@ public class NodeTypeOperation extends ToscaElementOperation {
return JanusGraphOperationStatus.OK;
}
- private JanusGraphOperationStatus setResourceDerivedFromGraph(final GraphVertex componentV,
- final NodeType toscaElement) {
+ private JanusGraphOperationStatus setResourceDerivedFromGraph(final GraphVertex componentV, final NodeType toscaElement) {
final List<String> derivedFromList = new ArrayList<>();
final Map<String, String> derivedFromMapOfIdToName = new LinkedHashMap<>();
-
- final JanusGraphOperationStatus listFromGraphStatus = findResourcesPathRecursively(componentV, derivedFromList,
- derivedFromMapOfIdToName);
+ final JanusGraphOperationStatus listFromGraphStatus = findResourcesPathRecursively(componentV, derivedFromList, derivedFromMapOfIdToName);
if (JanusGraphOperationStatus.OK != listFromGraphStatus) {
return listFromGraphStatus;
}
-
if (!derivedFromList.isEmpty()) {
if (derivedFromList.size() > 1) {
final List<String> lastDerivedFrom = new ArrayList<>();
@@ -347,30 +323,24 @@ public class NodeTypeOperation extends ToscaElementOperation {
return JanusGraphOperationStatus.OK;
}
- private JanusGraphOperationStatus findResourcesPathRecursively(final GraphVertex nodeTypeV,
- final List<String> resourcesPathList,
- final Map<String, String> derivedFromMapOfIdToName) {
+ private JanusGraphOperationStatus findResourcesPathRecursively(final GraphVertex nodeTypeV, final List<String> resourcesPathList,
+ final Map<String, String> derivedFromMapOfIdToName) {
Either<GraphVertex, JanusGraphOperationStatus> parentResourceRes = janusGraphDao
.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse);
resourcesPathList.add((String) nodeTypeV.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME));
- derivedFromMapOfIdToName.put(nodeTypeV.getUniqueId(),
- (String) nodeTypeV.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME));
+ derivedFromMapOfIdToName.put(nodeTypeV.getUniqueId(), (String) nodeTypeV.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME));
while (parentResourceRes.isLeft()) {
final GraphVertex parent = parentResourceRes.left().value();
resourcesPathList.add((String) parent.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME));
- derivedFromMapOfIdToName
- .put(parent.getUniqueId(), (String) parent.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME));
- parentResourceRes = janusGraphDao
- .getChildVertex(parent, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse);
+ derivedFromMapOfIdToName.put(parent.getUniqueId(), (String) parent.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME));
+ parentResourceRes = janusGraphDao.getChildVertex(parent, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse);
}
final JanusGraphOperationStatus operationStatus = parentResourceRes.right().value();
-
if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) {
return operationStatus;
} else {
return JanusGraphOperationStatus.OK;
}
-
}
protected <T extends ToscaElement> JanusGraphOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) {
@@ -378,7 +348,8 @@ public class NodeTypeOperation extends ToscaElementOperation {
}
private JanusGraphOperationStatus setResourceRequirementsFromGraph(GraphVertex componentV, NodeType toscaElement) {
- Either<Map<String, ListRequirementDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.REQUIREMENTS);
+ Either<Map<String, ListRequirementDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.REQUIREMENTS);
if (result.isLeft()) {
toscaElement.setRequirements(result.left().value());
} else {
@@ -415,9 +386,7 @@ public class NodeTypeOperation extends ToscaElementOperation {
private StorageOperationStatus assosiateToDerived(GraphVertex nodeTypeVertex, List<GraphVertex> derivedResources) {
for (GraphVertex derivedV : derivedResources) {
- JanusGraphOperationStatus
- createEdge = janusGraphDao
- .createEdge(nodeTypeVertex, derivedV, EdgeLabelEnum.DERIVED_FROM, null);
+ JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(nodeTypeVertex, derivedV, EdgeLabelEnum.DERIVED_FROM, null);
if (createEdge != JanusGraphOperationStatus.OK) {
log.trace("Failed to associate resource {} to derived with id {}", nodeTypeVertex.getUniqueId(), derivedV.getUniqueId());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
@@ -426,20 +395,22 @@ public class NodeTypeOperation extends ToscaElementOperation {
return StorageOperationStatus.OK;
}
- private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
+ private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, NodeType nodeType,
+ List<GraphVertex> derivedResources) {
// Note : currently only one derived supported!!!!
- Either<Map<String, AdditionalInfoParameterDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ADDITIONAL_INFORMATION);
+ Either<Map<String, AdditionalInfoParameterDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources,
+ EdgeLabelEnum.ADDITIONAL_INFORMATION);
if (dataFromDerived.isRight()) {
return dataFromDerived.right().value();
}
Map<String, AdditionalInfoParameterDataDefinition> addInformationAll = dataFromDerived.left().value();
-
Map<String, AdditionalInfoParameterDataDefinition> addInformation = nodeType.getAdditionalInformation();
if (addInformation != null) {
ToscaDataDefinition.mergeDataMaps(addInformationAll, addInformation);
}
if (!addInformationAll.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformationAll);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformationAll);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -447,14 +418,15 @@ public class NodeTypeOperation extends ToscaElementOperation {
return StorageOperationStatus.OK;
}
- private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
+ private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType,
+ List<GraphVertex> derivedResources) {
// Note : currently only one derived supported!!!!
- Either<Map<String, ListCapabilityDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES);
+ Either<Map<String, ListCapabilityDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources,
+ EdgeLabelEnum.CAPABILITIES);
if (dataFromDerived.isRight()) {
return dataFromDerived.right().value();
}
Map<String, ListCapabilityDataDefinition> capabiltiesAll = dataFromDerived.left().value();
-
Map<String, ListCapabilityDataDefinition> capabilties = nodeType.getCapabilities();
if (capabilties != null) {
if (capabiltiesAll == null) {
@@ -466,7 +438,6 @@ public class NodeTypeOperation extends ToscaElementOperation {
p.setUniqueId(uid);
});
});
-
ToscaDataDefinition.mergeDataMaps(capabiltiesAll, capabilties);
capabiltiesAll.values().forEach(l -> {
l.getListToscaDataDefinition().forEach(c -> {
@@ -490,7 +461,8 @@ public class NodeTypeOperation extends ToscaElementOperation {
});
});
if (!capabiltiesAll.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES, EdgeLabelEnum.CAPABILITIES, capabiltiesAll);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES,
+ EdgeLabelEnum.CAPABILITIES, capabiltiesAll);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -498,14 +470,15 @@ public class NodeTypeOperation extends ToscaElementOperation {
return StorageOperationStatus.OK;
}
- private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
+ private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, NodeType nodeType,
+ List<GraphVertex> derivedResources) {
// Note : currently only one derived supported!!!!
- Either<Map<String, ListRequirementDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.REQUIREMENTS);
+ Either<Map<String, ListRequirementDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources,
+ EdgeLabelEnum.REQUIREMENTS);
if (dataFromDerived.isRight()) {
return dataFromDerived.right().value();
}
Map<String, ListRequirementDataDefinition> requirementsAll = dataFromDerived.left().value();
-
Map<String, ListRequirementDataDefinition> requirements = nodeType.getRequirements();
if (requirements != null) {
if (requirementsAll == null) {
@@ -517,12 +490,11 @@ public class NodeTypeOperation extends ToscaElementOperation {
p.setUniqueId(uid);
});
});
-
ToscaDataDefinition.mergeDataMaps(requirementsAll, requirements);
-
}
if (!requirementsAll.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirementsAll);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS,
+ EdgeLabelEnum.REQUIREMENTS, requirementsAll);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -532,12 +504,12 @@ public class NodeTypeOperation extends ToscaElementOperation {
private StorageOperationStatus associateAttributesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
// Note : currently only one derived supported!!!!
- Either<Map<String, AttributeDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ATTRIBUTES);
+ Either<Map<String, AttributeDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources,
+ EdgeLabelEnum.ATTRIBUTES);
if (dataFromDerived.isRight()) {
return dataFromDerived.right().value();
}
Map<String, AttributeDataDefinition> attributesAll = dataFromDerived.left().value();
-
Map<String, AttributeDataDefinition> attributes = nodeType.getAttributes();
if (attributes != null) {
attributes.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
@@ -551,8 +523,8 @@ public class NodeTypeOperation extends ToscaElementOperation {
attributesAll.forEach((s, attributeDataDefinition) -> {
log.debug("Attribute {}:{}", s, attributeDataDefinition.getUniqueId());
});
-
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ATTRIBUTES, EdgeLabelEnum.ATTRIBUTES, attributesAll);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ATTRIBUTES,
+ EdgeLabelEnum.ATTRIBUTES, attributesAll);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -561,9 +533,11 @@ public class NodeTypeOperation extends ToscaElementOperation {
}
// TODO get from derived
- private StorageOperationStatus associateCapabilitiesPropertiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) {
+ private StorageOperationStatus associateCapabilitiesPropertiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType,
+ List<GraphVertex> derivedResources) {
// // Note : currently only one derived supported!!!!
- Either<Map<String, MapPropertiesDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES_PROPERTIES);
+ Either<Map<String, MapPropertiesDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources,
+ EdgeLabelEnum.CAPABILITIES_PROPERTIES);
if (dataFromDerived.isRight()) {
return dataFromDerived.right().value();
}
@@ -582,7 +556,8 @@ public class NodeTypeOperation extends ToscaElementOperation {
ToscaDataDefinition.mergeDataMaps(propertiesAll, capabiltiesProps);
}
if (!propertiesAll.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, propertiesAll);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, propertiesAll);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -591,18 +566,16 @@ public class NodeTypeOperation extends ToscaElementOperation {
}
public Either<List<GraphVertex>, StorageOperationStatus> findDerivedResources(NodeType nodeType) {
-
List<GraphVertex> derivedResources = new ArrayList<>();
List<String> derivedFromResources = nodeType.getDerivedFrom();
if (derivedFromResources != null && !derivedFromResources.isEmpty()) {
-
for (String parentResource : derivedFromResources) {
- Either<List<GraphVertex>, JanusGraphOperationStatus> getParentResources = derivedResourceResolver.findDerivedResources(parentResource);
+ Either<List<GraphVertex>, JanusGraphOperationStatus> getParentResources = derivedResourceResolver
+ .findDerivedResources(parentResource);
List<GraphVertex> resources = null;
if (getParentResources.isRight()) {
log.error("Cannot find parent resource by tosca resource name {} in the graph.", parentResource);
return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND);
-
} else {
resources = getParentResources.left().value();
if (resources == null || resources.size() == 0) {
@@ -610,50 +583,50 @@ public class NodeTypeOperation extends ToscaElementOperation {
return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND);
} else {
if (resources.size() > 1) {
- return handleMultipleParent(parentResource, derivedResources, resources, (String)nodeType.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE));
+ return handleMultipleParent(parentResource, derivedResources, resources,
+ (String) nodeType.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE));
} else {
GraphVertex parentResourceData = resources.get(0);
derivedResources.add(parentResourceData);
}
}
-
}
-
}
}
return Either.left(derivedResources);
}
- Either<List<GraphVertex>, StorageOperationStatus> handleMultipleParent(String parentResource, List<GraphVertex> derivedResource, List<GraphVertex> fetchedDerivedResources, String vendorRelease) {
-
+ Either<List<GraphVertex>, StorageOperationStatus> handleMultipleParent(String parentResource, List<GraphVertex> derivedResource,
+ List<GraphVertex> fetchedDerivedResources, String vendorRelease) {
Either<List<GraphVertex>, StorageOperationStatus> result = Either.left(derivedResource);
try {
fetchedDerivedResources.removeIf(graphVertex -> !isValidForVendorRelease(graphVertex, vendorRelease));
fetchedDerivedResources.sort((d1, d2) -> {
- return new Double(Double.parseDouble((String) d1.getMetadataProperty(GraphPropertyEnum.VERSION))).compareTo(Double.parseDouble((String) d2.getMetadataProperty(GraphPropertyEnum.VERSION)));
+ return new Double(Double.parseDouble((String) d1.getMetadataProperty(GraphPropertyEnum.VERSION)))
+ .compareTo(Double.parseDouble((String) d2.getMetadataProperty(GraphPropertyEnum.VERSION)));
});
-
int actualHighestIndex = fetchedDerivedResources.size() - 1;
derivedResource.add(fetchedDerivedResources.get(actualHighestIndex));
fetchedDerivedResources.remove(actualHighestIndex);
-
StorageOperationStatus status = fixMultipleParent(fetchedDerivedResources);
if (status != StorageOperationStatus.OK) {
result = Either.right(status);
}
} catch (Exception e) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during handle multiple parent {}. Exception is {}", parentResource, e.getMessage());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during handle multiple parent {}. Exception is {}", parentResource,
+ e.getMessage());
result = Either.right(StorageOperationStatus.GENERAL_ERROR);
}
return result;
}
-
+
private boolean isValidForVendorRelease(final GraphVertex resource, final String vendorRelease) {
if (vendorRelease != null && !vendorRelease.equals("1.0")) {
try {
- Semver resourceSemVer = new Semver((String)resource.getJsonMetadataField(JsonPresentationFields.VENDOR_RELEASE), SemverType.NPM);
+ Semver resourceSemVer = new Semver((String) resource.getJsonMetadataField(JsonPresentationFields.VENDOR_RELEASE), SemverType.NPM);
Semver packageSemVer = new Semver(vendorRelease, SemverType.NPM);
- return !resourceSemVer.isGreaterThan(packageSemVer);
+ return !resourceSemVer.isGreaterThan(packageSemVer);
} catch (Exception exception) {
log.debug("Error in comparing vendor release", exception);
return false;
@@ -669,7 +642,8 @@ public class NodeTypeOperation extends ToscaElementOperation {
Either<GraphVertex, JanusGraphOperationStatus> updateVertexRes = janusGraphDao.updateVertex(fetchedDerivedResource);
if (updateVertexRes.isRight()) {
JanusGraphOperationStatus titatStatus = updateVertexRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set highest version of node type {} to false. Status is {}", fetchedDerivedResource.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME), titatStatus);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set highest version of node type {} to false. Status is {}",
+ fetchedDerivedResource.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME), titatStatus);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(titatStatus);
break;
}
@@ -679,10 +653,8 @@ public class NodeTypeOperation extends ToscaElementOperation {
private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, NodeType nodeType) {
nodeTypeVertex.setLabel(VertexTypeEnum.NODE_TYPE);
-
fillCommonMetadata(nodeTypeVertex, nodeType);
nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.ATTRIBUTES, nodeType.getAttributes());
-
return nodeTypeVertex;
}
@@ -697,39 +669,33 @@ public class NodeTypeOperation extends ToscaElementOperation {
if (status != JanusGraphOperationStatus.OK) {
Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disassociate capabilties for {} error {}", toscaElementVertex.getUniqueId(), status);
Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES_PROPERTIES);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES_PROPERTIES);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disassociate capabilties properties for {} error {}", toscaElementVertex.getUniqueId(), status);
Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disassociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disassociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE_ARTIFACTS);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE_ARTIFACTS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disassociate interface artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
toscaElementVertex.getVertex().remove();
log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId());
-
return nodeType;
}
@@ -751,11 +717,8 @@ public class NodeTypeOperation extends ToscaElementOperation {
@Override
protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV) {
-
NodeType nodeType = (NodeType) toscaElementToUpdate;
-
List<String> derivedFromResources = nodeType.getDerivedFrom();
-
// now supported only single derived from
if (derivedFromResources != null && !derivedFromResources.isEmpty() && derivedFromResources.get(0) != null) {
String firstDerived = derivedFromResources.get(0);
@@ -768,22 +731,18 @@ public class NodeTypeOperation extends ToscaElementOperation {
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getchieldError);
}
GraphVertex firstDerivedInChain = childVertex.left().value();
-
String firstCurrentDerived = (String) firstDerivedInChain.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME);
if (!firstDerived.equals(firstCurrentDerived) || derivedFromGenericType) {
-
Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
-
propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, firstDerived);
propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
Either<List<GraphVertex>, JanusGraphOperationStatus> getParentResources = janusGraphDao
.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.NoParse);
-
if (getParentResources.isRight()) {
JanusGraphOperationStatus error = getParentResources.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch derived by criteria {}. error {} ", propertiesToMatch, error);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch derived by criteria {}. error {} ", propertiesToMatch, error);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error);
}
// must be only one
@@ -795,7 +754,6 @@ public class NodeTypeOperation extends ToscaElementOperation {
}
/**
- *
* @param toscaElementToUpdate
* @param nodeTypeV
* @param preDerivedV
@@ -803,7 +761,8 @@ public class NodeTypeOperation extends ToscaElementOperation {
* @param mergeValues
* @return
*/
- protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV, GraphVertex preDerivedV, GraphVertex newDerivedV, boolean mergeValues) {
+ protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV, GraphVertex preDerivedV,
+ GraphVertex newDerivedV, boolean mergeValues) {
Set<String> preDerivedChainIdList = new HashSet();
preDerivedChainIdList.add(preDerivedV.getUniqueId());
Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
@@ -811,54 +770,53 @@ public class NodeTypeOperation extends ToscaElementOperation {
while (childVertex.isLeft()) {
GraphVertex currentChield = childVertex.left().value();
preDerivedChainIdList.add(currentChield.getUniqueId());
- childVertex = janusGraphDao
- .getChildVertex(currentChield, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse);
+ childVertex = janusGraphDao.getChildVertex(currentChield, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse);
}
-
List<GraphVertex> derivedResources = new ArrayList<>();
derivedResources.add(newDerivedV);
- StorageOperationStatus updateStatus = updateDataFromNewDerived(derivedResources, nodeTypeV, (NodeType) toscaElementToUpdate, mergeValues, preDerivedChainIdList);
+ StorageOperationStatus updateStatus = updateDataFromNewDerived(derivedResources, nodeTypeV, (NodeType) toscaElementToUpdate, mergeValues,
+ preDerivedChainIdList);
if (updateStatus != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update data for {} from new derived {} ", nodeTypeV.getUniqueId(), newDerivedV.getUniqueId(), updateStatus);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update data for {} from new derived {} ", nodeTypeV.getUniqueId(),
+ newDerivedV.getUniqueId(), updateStatus);
return updateStatus;
}
-
- Either<Edge, JanusGraphOperationStatus> deleteEdge = janusGraphDao
- .deleteEdge(nodeTypeV, preDerivedV, EdgeLabelEnum.DERIVED_FROM);
+ Either<Edge, JanusGraphOperationStatus> deleteEdge = janusGraphDao.deleteEdge(nodeTypeV, preDerivedV, EdgeLabelEnum.DERIVED_FROM);
if (deleteEdge.isRight()) {
JanusGraphOperationStatus deleteError = deleteEdge.right().value();
- log.debug("Failed to disassociate element {} from derived {} , error {}", nodeTypeV.getUniqueId(), preDerivedV.getUniqueId(), deleteError);
+ log.debug("Failed to disassociate element {} from derived {} , error {}", nodeTypeV.getUniqueId(), preDerivedV.getUniqueId(),
+ deleteError);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteError);
}
-
janusGraphDao.createEdge(nodeTypeV, newDerivedV, EdgeLabelEnum.DERIVED_FROM, new HashMap<>());
-
return StorageOperationStatus.OK;
}
- private StorageOperationStatus associateDerivedDataByType(EdgeLabelEnum edgeLabel, GraphVertex nodeTypeV, NodeType nodeToUpdate, List<GraphVertex> newDerived) {
-
+ private StorageOperationStatus associateDerivedDataByType(EdgeLabelEnum edgeLabel, GraphVertex nodeTypeV, NodeType nodeToUpdate,
+ List<GraphVertex> newDerived) {
switch (edgeLabel) {
- case CAPABILITIES:
- return associateCapabilitiesToResource(nodeTypeV, nodeToUpdate, newDerived);
- case REQUIREMENTS:
- return associateRequirementsToResource(nodeTypeV, nodeToUpdate, newDerived);
- case PROPERTIES:
- return associatePropertiesToResource(nodeTypeV, nodeToUpdate, newDerived);
- case ATTRIBUTES:
- return associateAttributesToResource(nodeTypeV, nodeToUpdate, newDerived);
- case ADDITIONAL_INFORMATION:
- return addAdditionalInformationToResource(nodeTypeV, nodeToUpdate, newDerived);
- case CAPABILITIES_PROPERTIES:
- return associateCapabilitiesPropertiesToResource(nodeTypeV, nodeToUpdate, newDerived);
- default:
- return StorageOperationStatus.OK;
- }
-
- }
-
- private StorageOperationStatus updateDataFromNewDerived(List<GraphVertex> newDerived, GraphVertex nodeTypeV, NodeType nodeToUpdate, boolean mergeValues, Set<String> preDerivedChainIdList) {
- EnumSet<EdgeLabelEnum> edgeLabels = EnumSet.of(EdgeLabelEnum.CAPABILITIES, EdgeLabelEnum.REQUIREMENTS, EdgeLabelEnum.PROPERTIES, EdgeLabelEnum.ATTRIBUTES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.ADDITIONAL_INFORMATION);
+ case CAPABILITIES:
+ return associateCapabilitiesToResource(nodeTypeV, nodeToUpdate, newDerived);
+ case REQUIREMENTS:
+ return associateRequirementsToResource(nodeTypeV, nodeToUpdate, newDerived);
+ case PROPERTIES:
+ return associatePropertiesToResource(nodeTypeV, nodeToUpdate, newDerived);
+ case ATTRIBUTES:
+ return associateAttributesToResource(nodeTypeV, nodeToUpdate, newDerived);
+ case ADDITIONAL_INFORMATION:
+ return addAdditionalInformationToResource(nodeTypeV, nodeToUpdate, newDerived);
+ case CAPABILITIES_PROPERTIES:
+ return associateCapabilitiesPropertiesToResource(nodeTypeV, nodeToUpdate, newDerived);
+ default:
+ return StorageOperationStatus.OK;
+ }
+ }
+
+ private StorageOperationStatus updateDataFromNewDerived(List<GraphVertex> newDerived, GraphVertex nodeTypeV, NodeType nodeToUpdate,
+ boolean mergeValues, Set<String> preDerivedChainIdList) {
+ EnumSet<EdgeLabelEnum> edgeLabels = EnumSet
+ .of(EdgeLabelEnum.CAPABILITIES, EdgeLabelEnum.REQUIREMENTS, EdgeLabelEnum.PROPERTIES, EdgeLabelEnum.ATTRIBUTES,
+ EdgeLabelEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.ADDITIONAL_INFORMATION);
StorageOperationStatus status = null;
for (EdgeLabelEnum edge : edgeLabels) {
status = updateDataByType(newDerived, nodeTypeV, edge, nodeToUpdate, mergeValues, preDerivedChainIdList);
@@ -867,24 +825,26 @@ public class NodeTypeOperation extends ToscaElementOperation {
}
}
return status;
-
}
- private <T extends ToscaDataDefinition> StorageOperationStatus updateDataByType(List<GraphVertex> newDerivedList, GraphVertex nodeTypeV, EdgeLabelEnum label, NodeType nodeElement, boolean mergeValues, Set<String> preDerivedChainIdList) {
+ private <T extends ToscaDataDefinition> StorageOperationStatus updateDataByType(List<GraphVertex> newDerivedList, GraphVertex nodeTypeV,
+ EdgeLabelEnum label, NodeType nodeElement, boolean mergeValues,
+ Set<String> preDerivedChainIdList) {
log.debug("Update data from derived for element {} type {}", nodeTypeV.getUniqueId(), label);
Either<GraphVertex, JanusGraphOperationStatus> dataFromGraph = getDataVertex(nodeTypeV, label);
if (dataFromGraph.isRight()) {
- if (JanusGraphOperationStatus.NOT_FOUND == dataFromGraph.right().value())
+ if (JanusGraphOperationStatus.NOT_FOUND == dataFromGraph.right().value()) {
return associateDerivedDataByType(label, nodeTypeV, nodeElement, newDerivedList);
+ }
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(dataFromGraph.right().value());
}
GraphVertex dataV = dataFromGraph.left().value();
-
Map<String, T> mapFromGraph = (Map<String, T>) dataV.getJson();
Map<String, T> valuesFrmPrev = null;
if (isSimpleHierarchy(label)) {
if (mergeValues) {
- valuesFrmPrev = mapFromGraph.entrySet().stream().filter(e -> e.getValue().getOwnerId() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ valuesFrmPrev = mapFromGraph.entrySet().stream().filter(e -> e.getValue().getOwnerId() != null)
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
mapFromGraph.entrySet().removeIf(e -> preDerivedChainIdList.contains(e.getValue().getOwnerId()));
} else {
@@ -895,15 +855,13 @@ public class NodeTypeOperation extends ToscaElementOperation {
valuesFrmPrevFinal.put(e.getKey(), value);
});
valuesFrmPrev = valuesFrmPrevFinal;
- mapFromGraph.entrySet().removeIf(e->e.getValue().isEmpty());
+ mapFromGraph.entrySet().removeIf(e -> e.getValue().isEmpty());
}
-
Either<Map<String, T>, StorageOperationStatus> dataFromDerived = getDataFromDerived(newDerivedList, label);
if (dataFromDerived.isRight()) {
return dataFromDerived.right().value();
}
Map<String, T> dataFromDerivedAll = dataFromDerived.left().value();
-
Either<Map<String, T>, String> merged = ToscaDataDefinition.mergeDataMaps(dataFromDerivedAll, mapFromGraph);
if (merged.isRight()) {
log.debug("property {} cannot be overriden", merged.right().value());
@@ -915,7 +873,7 @@ public class NodeTypeOperation extends ToscaElementOperation {
if (newData != null) {
if (isSimpleHierarchy(label)) {
e.getValue().mergeFunction(newData, true);
- }else{
+ } else {
e.getValue().updateIfExist(newData, true);
}
}
@@ -931,16 +889,16 @@ public class NodeTypeOperation extends ToscaElementOperation {
private boolean isSimpleHierarchy(EdgeLabelEnum label) {
switch (label) {
- case PROPERTIES:
- case ATTRIBUTES:
- case ADDITIONAL_INFORMATION:
- case ARTIFACTS:
- case GROUPS:
- case INPUTS:
- case OUTPUTS:
- return true;
- default:
- return false;
+ case PROPERTIES:
+ case ATTRIBUTES:
+ case ADDITIONAL_INFORMATION:
+ case ARTIFACTS:
+ case GROUPS:
+ case INPUTS:
+ case OUTPUTS:
+ return true;
+ default:
+ return false;
}
}
@@ -951,7 +909,6 @@ public class NodeTypeOperation extends ToscaElementOperation {
public Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion(ToscaElement toscaElementToUpdate, GraphVertex nodeTypeV) {
NodeType nodeType = (NodeType) toscaElementToUpdate;
-
Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
@@ -960,19 +917,15 @@ public class NodeTypeOperation extends ToscaElementOperation {
log.debug("derived resource for element {} not found", nodeTypeV.getUniqueId());
return Either.right(StorageOperationStatus.OK);
}
-
log.debug("Failed to fetch derived resource for element {} error {}", nodeTypeV.getUniqueId(), getchildError);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getchildError));
}
GraphVertex firstDerivedInChain = childVertex.left().value();
-
String currentVersion = (String) firstDerivedInChain.getMetadataProperty(GraphPropertyEnum.VERSION);
-
Map<GraphPropertyEnum, Object> props = new HashMap<>();
props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, nodeType.getDerivedFrom().get(0));
props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
Map<GraphPropertyEnum, Object> propsHasNot = new HashMap<>();
propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> byCriteria = janusGraphDao
@@ -986,12 +939,11 @@ public class NodeTypeOperation extends ToscaElementOperation {
GraphVertex derivedFromHighest = lastDerived.get(0);
String highestVersion = (String) derivedFromHighest.getMetadataProperty(GraphPropertyEnum.VERSION);
if (!highestVersion.equals(currentVersion)) {
-
// need to update to latest version of derived from
StorageOperationStatus updateDerived = updateDerived(toscaElementToUpdate, nodeTypeV, firstDerivedInChain, derivedFromHighest, true);
-
if (updateDerived != StorageOperationStatus.OK) {
- log.debug("Failed to update {} to highest derived {} from error {}", nodeTypeV.getUniqueId(), derivedFromHighest.getUniqueId(), updateDerived);
+ log.debug("Failed to update {} to highest derived {} from error {}", nodeTypeV.getUniqueId(), derivedFromHighest.getUniqueId(),
+ updateDerived);
return Either.right(updateDerived);
}
return getToscaElement(nodeTypeV.getUniqueId(), new ComponentParametersView());
@@ -999,5 +951,4 @@ public class NodeTypeOperation extends ToscaElementOperation {
// no version changes
return Either.right(StorageOperationStatus.OK);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperation.java
index ed9e480ed6..f40b19a083 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/PolicyOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.jsonjanusgraph.operations;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
@@ -31,10 +33,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
@org.springframework.stereotype.Component
public class PolicyOperation {
@@ -49,34 +47,38 @@ public class PolicyOperation {
/**
* updates a list of policy properties by overriding the existing ones with the same name
+ *
* @param containerComponent the container of the policy of which its properties are to be updated
- * @param policyId the id of the policy of which its properties are to be updated
+ * @param policyId the id of the policy of which its properties are to be updated
* @param propertiesToUpdate the policy properties to update
* @return the update operation status
*/
- public StorageOperationStatus updatePolicyProperties(Component containerComponent, String policyId, List<PropertyDataDefinition> propertiesToUpdate) {
+ public StorageOperationStatus updatePolicyProperties(Component containerComponent, String policyId,
+ List<PropertyDataDefinition> propertiesToUpdate) {
log.debug("#updatePolicyProperties - updating the properties of policy {} in component {}", policyId, containerComponent.getUniqueId());
PolicyDefinition policy = containerComponent.getPolicyById(policyId);
return janusGraphDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.NoParse)
- .either(containerVertex -> updatePolicyProperties(containerVertex, policy, propertiesToUpdate),
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .either(containerVertex -> updatePolicyProperties(containerVertex, policy, propertiesToUpdate),
+ DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
- private StorageOperationStatus updatePolicyProperties(GraphVertex container, PolicyDefinition policy, List<PropertyDataDefinition> propertiesToUpdate) {
+ private StorageOperationStatus updatePolicyProperties(GraphVertex container, PolicyDefinition policy,
+ List<PropertyDataDefinition> propertiesToUpdate) {
List<PropertyDataDefinition> policyProperties = policy.getProperties();
List<PropertyDataDefinition> updatedPolicyProperties = updatePolicyProperties(policyProperties, propertiesToUpdate);
policy.setProperties(updatedPolicyProperties);
return topologyTemplateOperation.updatePolicyOfToscaElement(container, policy);
}
- private List<PropertyDataDefinition> updatePolicyProperties(List<PropertyDataDefinition> currentPolicyProperties, List<PropertyDataDefinition> toBeUpdatedProperties) {
+ private List<PropertyDataDefinition> updatePolicyProperties(List<PropertyDataDefinition> currentPolicyProperties,
+ List<PropertyDataDefinition> toBeUpdatedProperties) {
Map<String, PropertyDataDefinition> currPropsByName = MapUtil.toMap(currentPolicyProperties, PropertyDataDefinition::getName);
overrideCurrentPropertiesWithUpdatedProperties(currPropsByName, toBeUpdatedProperties);
return new ArrayList<>(currPropsByName.values());
}
- private void overrideCurrentPropertiesWithUpdatedProperties(Map<String, PropertyDataDefinition> currPropsByName, List<PropertyDataDefinition> toBeUpdatedProperties) {
+ private void overrideCurrentPropertiesWithUpdatedProperties(Map<String, PropertyDataDefinition> currPropsByName,
+ List<PropertyDataDefinition> toBeUpdatedProperties) {
toBeUpdatedProperties.forEach(prop -> currPropsByName.put(prop.getName(), prop));
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/RequirementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/RequirementOperation.java
index 9c1d1eec3b..050e4b8faa 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/RequirementOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/RequirementOperation.java
@@ -13,10 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
@@ -28,65 +30,51 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
@org.springframework.stereotype.Component("requirement-operation")
public class RequirementOperation extends BaseOperation {
+
private static final Logger LOGGER = LoggerFactory.getLogger(RequirementOperation.class);
- public Either<List<RequirementDefinition>, StorageOperationStatus> addRequirement(
- String componentId,
- List<RequirementDefinition> requirementDefinitions) {
- return addOrUpdateRequirements( componentId, requirementDefinitions, false);
+ private static ListRequirementDataDefinition convertToListRequirementDataDefinition(List<RequirementDefinition> requirementDefinitions) {
+ List<RequirementDataDefinition> requirementDataDefinitions = new ArrayList<>(requirementDefinitions);
+ return new ListRequirementDataDefinition(requirementDataDefinitions);
}
- public Either<List<RequirementDefinition>, StorageOperationStatus> updateRequirement(
- String componentId,
- List<RequirementDefinition> requirementDefinitions) {
- return addOrUpdateRequirements( componentId, requirementDefinitions, true);
+ public Either<List<RequirementDefinition>, StorageOperationStatus> addRequirement(String componentId,
+ List<RequirementDefinition> requirementDefinitions) {
+ return addOrUpdateRequirements(componentId, requirementDefinitions, false);
}
+ public Either<List<RequirementDefinition>, StorageOperationStatus> updateRequirement(String componentId,
+ List<RequirementDefinition> requirementDefinitions) {
+ return addOrUpdateRequirements(componentId, requirementDefinitions, true);
+ }
private Either<List<RequirementDefinition>, StorageOperationStatus> addOrUpdateRequirements(String componentId,
- List<RequirementDefinition> requirementDefinitions,
+ List<RequirementDefinition> requirementDefinitions,
boolean isUpdateAction) {
-
- StorageOperationStatus statusRes = performUpdateToscaAction(isUpdateAction,
- componentId, Collections
- .singletonList(convertToListRequirementDataDefinition(requirementDefinitions)));
+ StorageOperationStatus statusRes = performUpdateToscaAction(isUpdateAction, componentId,
+ Collections.singletonList(convertToListRequirementDataDefinition(requirementDefinitions)));
if (!statusRes.equals(StorageOperationStatus.OK)) {
janusGraphDao.rollback();
- LOGGER.error("Failed to find the parent capability of capability type {}."
- + " status is {}", componentId, statusRes);
+ LOGGER.error("Failed to find the parent capability of capability type {}." + " status is {}", componentId, statusRes);
return Either.right(statusRes);
}
janusGraphDao.commit();
return Either.left(requirementDefinitions);
}
- public StorageOperationStatus deleteRequirements(Component component,
- String requirementToDelete) {
- return deleteToscaDataElements(component.getUniqueId(),
- EdgeLabelEnum.REQUIREMENTS, Collections.singletonList(requirementToDelete));
- }
-
- private static ListRequirementDataDefinition convertToListRequirementDataDefinition(
- List<RequirementDefinition> requirementDefinitions) {
- List<RequirementDataDefinition> requirementDataDefinitions =
- new ArrayList<>(requirementDefinitions);
- return new ListRequirementDataDefinition(requirementDataDefinitions);
+ public StorageOperationStatus deleteRequirements(Component component, String requirementToDelete) {
+ return deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.REQUIREMENTS, Collections.singletonList(requirementToDelete));
}
- private StorageOperationStatus performUpdateToscaAction(boolean isUpdate,
- String componentId, List<ListRequirementDataDefinition> toscaDataList) {
+ private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, String componentId, List<ListRequirementDataDefinition> toscaDataList) {
if (isUpdate) {
- return updateToscaDataOfToscaElement(componentId, EdgeLabelEnum.REQUIREMENTS,
- VertexTypeEnum.REQUIREMENTS, toscaDataList, JsonPresentationFields.CAPABILITY);
+ return updateToscaDataOfToscaElement(componentId, EdgeLabelEnum.REQUIREMENTS, VertexTypeEnum.REQUIREMENTS, toscaDataList,
+ JsonPresentationFields.CAPABILITY);
} else {
- return addToscaDataToToscaElement(componentId, EdgeLabelEnum.REQUIREMENTS,
- VertexTypeEnum.REQUIREMENTS, toscaDataList, JsonPresentationFields.CAPABILITY);
+ return addToscaDataToToscaElement(componentId, EdgeLabelEnum.REQUIREMENTS, VertexTypeEnum.REQUIREMENTS, toscaDataList,
+ JsonPresentationFields.CAPABILITY);
}
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/SubstitutionFilterOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/SubstitutionFilterOperation.java
index 0062e2eaa7..b4873fa78a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/SubstitutionFilterOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/SubstitutionFilterOperation.java
@@ -16,7 +16,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import com.google.common.collect.ImmutableList;
@@ -44,59 +43,50 @@ public class SubstitutionFilterOperation extends BaseOperation {
private static final Logger LOGGER = Logger.getLogger(SubstitutionFilterOperation.class);
- public Either<SubstitutionFilterDataDefinition, StorageOperationStatus> createSubstitutionFilter(
- final String componentId) {
-
+ public Either<SubstitutionFilterDataDefinition, StorageOperationStatus> createSubstitutionFilter(final String componentId) {
return addOrUpdateSubstitutionFilter(false, componentId, new SubstitutionFilterDataDefinition());
}
- public Either<SubstitutionFilterDataDefinition, StorageOperationStatus> deleteConstraint(
- final String serviceId, final SubstitutionFilterDataDefinition substitutionFilterDataDefinition,
- final int propertyIndex) {
-
- final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> properties =
- substitutionFilterDataDefinition.getProperties();
+ public Either<SubstitutionFilterDataDefinition, StorageOperationStatus> deleteConstraint(final String serviceId,
+ final SubstitutionFilterDataDefinition substitutionFilterDataDefinition,
+ final int propertyIndex) {
+ final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> properties = substitutionFilterDataDefinition.getProperties();
properties.getListToscaDataDefinition().remove(propertyIndex);
substitutionFilterDataDefinition.setProperties(properties);
-
return addOrUpdateSubstitutionFilter(true, serviceId, substitutionFilterDataDefinition);
}
- public Either<SubstitutionFilterDataDefinition, StorageOperationStatus> addPropertyFilter(
- final String componentId, final SubstitutionFilterDataDefinition substitutionFilterDataDefinition,
- final RequirementSubstitutionFilterPropertyDataDefinition substitutionFilterPropertyDataDefinition) {
-
- final SubstitutionFilterDataDefinition substitutionFilterDataDefinition1 =
- Objects.requireNonNullElseGet(substitutionFilterDataDefinition, SubstitutionFilterDataDefinition::new);
- final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> properties =
- Objects.requireNonNullElseGet(substitutionFilterDataDefinition1.getProperties(), ListDataDefinition::new);
+ public Either<SubstitutionFilterDataDefinition, StorageOperationStatus> addPropertyFilter(final String componentId,
+ final SubstitutionFilterDataDefinition substitutionFilterDataDefinition,
+ final RequirementSubstitutionFilterPropertyDataDefinition substitutionFilterPropertyDataDefinition) {
+ final SubstitutionFilterDataDefinition substitutionFilterDataDefinition1 = Objects
+ .requireNonNullElseGet(substitutionFilterDataDefinition, SubstitutionFilterDataDefinition::new);
+ final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> properties = Objects
+ .requireNonNullElseGet(substitutionFilterDataDefinition1.getProperties(), ListDataDefinition::new);
properties.getListToscaDataDefinition().add(substitutionFilterPropertyDataDefinition);
substitutionFilterDataDefinition1.setProperties(properties);
return addOrUpdateSubstitutionFilter(true, componentId, substitutionFilterDataDefinition1);
}
- public Either<SubstitutionFilterDataDefinition, StorageOperationStatus> updateProperties(
- final String componentId, final SubstitutionFilterDataDefinition substitutionFilterDataDefinition,
- final List<RequirementSubstitutionFilterPropertyDataDefinition> requirementSubstitutionFilterPropertyDataDefinition) {
-
- final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> properties =
- substitutionFilterDataDefinition.getProperties();
+ public Either<SubstitutionFilterDataDefinition, StorageOperationStatus> updateProperties(final String componentId,
+ final SubstitutionFilterDataDefinition substitutionFilterDataDefinition,
+ final List<RequirementSubstitutionFilterPropertyDataDefinition> requirementSubstitutionFilterPropertyDataDefinition) {
+ final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> properties = substitutionFilterDataDefinition.getProperties();
properties.getListToscaDataDefinition().clear();
properties.getListToscaDataDefinition().addAll(requirementSubstitutionFilterPropertyDataDefinition);
substitutionFilterDataDefinition.setProperties(properties);
return addOrUpdateSubstitutionFilter(true, componentId, substitutionFilterDataDefinition);
}
- private Either<SubstitutionFilterDataDefinition, StorageOperationStatus> addOrUpdateSubstitutionFilter(
- final boolean isUpdateAction, final String componentId,
- final SubstitutionFilterDataDefinition substitutionFilterDataDefinition) {
-
- final Either<GraphVertex, JanusGraphOperationStatus> toscaElementEither =
- janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ private Either<SubstitutionFilterDataDefinition, StorageOperationStatus> addOrUpdateSubstitutionFilter(final boolean isUpdateAction,
+ final String componentId,
+ final SubstitutionFilterDataDefinition substitutionFilterDataDefinition) {
+ final Either<GraphVertex, JanusGraphOperationStatus> toscaElementEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (toscaElementEither.isRight()) {
final JanusGraphOperationStatus status = toscaElementEither.right().value();
- CommonUtility.addRecordToLog(LOGGER, CommonUtility.LogLevelEnum.DEBUG,
- "Failed to get tosca element {} upon adding the properties. Status is {}. ", componentId, status);
+ CommonUtility
+ .addRecordToLog(LOGGER, CommonUtility.LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ",
+ componentId, status);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
final GraphVertex serviceVertex = toscaElementEither.left().value();
@@ -106,27 +96,22 @@ public class SubstitutionFilterOperation extends BaseOperation {
if (!StorageOperationStatus.OK.equals(operationStatus)) {
janusGraphDao.rollback();
LOGGER.error(EcompErrorSeverity.ERROR, EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR,
- " Failed to perform tosca update for substitution filter in service {} , component instance {}. status is {}",
- componentId, "componentInstanceId", operationStatus);
+ " Failed to perform tosca update for substitution filter in service {} , component instance {}. status is {}", componentId,
+ "componentInstanceId", operationStatus);
return Either.right(operationStatus);
}
janusGraphDao.commit();
return Either.left(substitutionFilterDataDefinition);
}
- private StorageOperationStatus performUpdateToscaAction(final boolean isUpdate,
- final GraphVertex graphVertex,
+ private StorageOperationStatus performUpdateToscaAction(final boolean isUpdate, final GraphVertex graphVertex,
final List<SubstitutionFilterDataDefinition> toscaDataList) {
if (isUpdate) {
- return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.SUBSTITUTION_FILTER_TEMPLATE,
- VertexTypeEnum.SUBSTITUTION_FILTER_TEMPLATE, toscaDataList, JsonPresentationFields.UNIQUE_ID);
+ return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.SUBSTITUTION_FILTER_TEMPLATE, VertexTypeEnum.SUBSTITUTION_FILTER_TEMPLATE,
+ toscaDataList, JsonPresentationFields.UNIQUE_ID);
} else {
- return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.SUBSTITUTION_FILTER_TEMPLATE,
- VertexTypeEnum.SUBSTITUTION_FILTER_TEMPLATE, toscaDataList, JsonPresentationFields.UNIQUE_ID);
+ return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.SUBSTITUTION_FILTER_TEMPLATE, VertexTypeEnum.SUBSTITUTION_FILTER_TEMPLATE,
+ toscaDataList, JsonPresentationFields.UNIQUE_ID);
}
}
-
}
-
-
-
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java
index c2cd29d76f..0ca76b5304 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java
@@ -17,14 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import com.google.gson.reflect.TypeToken;
import fj.data.Either;
import java.lang.reflect.Type;
-import java.util.*;
+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.Optional;
import java.util.stream.Collectors;
import org.apache.commons.collections.MapUtils;
import org.apache.tinkerpop.gremlin.structure.Direction;
@@ -35,12 +39,9 @@ import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.datatypes.category.MetadataKeyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty;
-import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
@@ -51,9 +52,12 @@ import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty;
import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
@@ -88,45 +92,43 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
-
@org.springframework.stereotype.Component("topology-template-operation")
public class TopologyTemplateOperation extends ToscaElementOperation {
private static final Logger log = Logger.getLogger(TopologyTemplateOperation.class);
-
@Autowired
private ArchiveOperation archiveOperation;
+ public static String buildSubComponentName(String componentName, String subComponentTypeName, int counter) {
+ String normalizedComponentName = ValidationUtils.normalizeComponentInstanceName(componentName);
+ String typeSuffix = subComponentTypeName.substring(subComponentTypeName.lastIndexOf('.') + 1, subComponentTypeName.length());
+ return normalizedComponentName + Constants.GROUP_POLICY_NAME_DELIMETER + typeSuffix + Constants.GROUP_POLICY_NAME_DELIMETER + counter;
+ }
+
public Either<TopologyTemplate, StorageOperationStatus> createTopologyTemplate(TopologyTemplate topologyTemplate) {
topologyTemplate.generateUUID();
-
topologyTemplate = getResourceMetaDataFromResource(topologyTemplate);
String resourceUniqueId = topologyTemplate.getUniqueId();
if (resourceUniqueId == null) {
resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId();
topologyTemplate.setUniqueId(resourceUniqueId);
}
-
GraphVertex topologyTemplateVertex = new GraphVertex();
topologyTemplateVertex = fillMetadata(topologyTemplateVertex, topologyTemplate, JsonParseFlagEnum.ParseAll);
-
Either<GraphVertex, JanusGraphOperationStatus> createdVertex = janusGraphDao.createVertex(topologyTemplateVertex);
if (createdVertex.isRight()) {
JanusGraphOperationStatus status = createdVertex.right().value();
- log.debug( "Error returned after creating topology template data node {}. status returned is ", topologyTemplateVertex, status);
+ log.debug("Error returned after creating topology template data node {}. status returned is ", topologyTemplateVertex, status);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(topologyTemplateVertex, topologyTemplate);
if (assosiateCommon != StorageOperationStatus.OK) {
return Either.right(assosiateCommon);
}
-
StorageOperationStatus associateCategory = assosiateMetadataToCategory(topologyTemplateVertex, topologyTemplate);
if (associateCategory != StorageOperationStatus.OK) {
return Either.right(associateCategory);
}
-
StorageOperationStatus associateInputs = associateInputsToComponent(topologyTemplateVertex, topologyTemplate);
if (associateInputs != StorageOperationStatus.OK) {
return Either.right(associateInputs);
@@ -155,22 +157,18 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
if (associateInstGroups != StorageOperationStatus.OK) {
return Either.right(associateInstInputs);
}
-
StorageOperationStatus associateRequirements = associateRequirementsToResource(topologyTemplateVertex, topologyTemplate);
if (associateRequirements != StorageOperationStatus.OK) {
return Either.right(associateRequirements);
}
-
StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(topologyTemplateVertex, topologyTemplate);
if (associateCapabilities != StorageOperationStatus.OK) {
return Either.right(associateCapabilities);
}
-
StorageOperationStatus associateArtifacts = associateTopologyTemplateArtifactsToComponent(topologyTemplateVertex, topologyTemplate);
if (associateArtifacts != StorageOperationStatus.OK) {
return Either.right(associateArtifacts);
}
-
StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(topologyTemplateVertex, topologyTemplate);
if (addAdditionalInformation != StorageOperationStatus.OK) {
return Either.right(addAdditionalInformation);
@@ -179,12 +177,10 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
if (associateCapProperties != StorageOperationStatus.OK) {
return Either.right(associateCapProperties);
}
-
StorageOperationStatus associateInterfaces = associateInterfacesToComponent(topologyTemplateVertex, topologyTemplate);
if (associateInterfaces != StorageOperationStatus.OK) {
return Either.right(associateInterfaces);
}
-
StorageOperationStatus associatePathProperties = associateForwardingPathToResource(topologyTemplateVertex, topologyTemplate);
if (associateCapProperties != StorageOperationStatus.OK) {
return Either.right(associatePathProperties);
@@ -196,13 +192,14 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return associatePoliciesToComponent(nodeTypeVertex, topologyTemplate.getPolicies());
}
- private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, Map<String, PolicyDataDefinition> policies) {
+ private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, Map<String, PolicyDataDefinition> policies) {
if (policies != null && !policies.isEmpty()) {
policies.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName());
p.setUniqueId(uid);
});
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.POLICIES, EdgeLabelEnum.POLICIES, policies);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.POLICIES,
+ EdgeLabelEnum.POLICIES, policies);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -212,26 +209,22 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
private StorageOperationStatus associateForwardingPathToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
Map<String, ForwardingPathDataDefinition> forwardingPaths = topologyTemplate.getForwardingPaths();
- return associateForwardingPathToComponent(topologyTemplateVertex,forwardingPaths);
+ return associateForwardingPathToComponent(topologyTemplateVertex, forwardingPaths);
}
private StorageOperationStatus associateCapPropertiesToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
- Map<String, MapCapabilityProperty> calculatedCapProperties = topologyTemplate
- .getCalculatedCapabilitiesProperties();
+ Map<String, MapCapabilityProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties();
if (MapUtils.isNotEmpty(calculatedCapProperties)) {
- Either<GraphVertex, StorageOperationStatus> associateElementToData = associateElementToData
- (topologyTemplateVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,
- EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapProperties);
+ Either<GraphVertex, StorageOperationStatus> associateElementToData = associateElementToData(topologyTemplateVertex,
+ VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapProperties);
if (associateElementToData.isRight()) {
return associateElementToData.right().value();
}
}
-
Map<String, MapPropertiesDataDefinition> capabilitiesProperties = topologyTemplate.getCapabilitiesProperties();
if (MapUtils.isNotEmpty(capabilitiesProperties)) {
- Either<GraphVertex, StorageOperationStatus> associateElementToData =
- associateElementToData(topologyTemplateVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES,
- EdgeLabelEnum.CAPABILITIES_PROPERTIES, capabilitiesProperties);
+ Either<GraphVertex, StorageOperationStatus> associateElementToData = associateElementToData(topologyTemplateVertex,
+ VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, capabilitiesProperties);
if (associateElementToData.isRight()) {
return associateElementToData.right().value();
}
@@ -242,51 +235,52 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
Map<String, MapListCapabilityDataDefinition> calculatedCapabilities = topologyTemplate.getCalculatedCapabilities();
if (calculatedCapabilities != null && !calculatedCapabilities.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calculatedCapabilities);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calculatedCapabilities);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
}
Map<String, MapListCapabilityDataDefinition> fullfilledCapabilities = topologyTemplate.getFullfilledCapabilities();
if (fullfilledCapabilities != null && !fullfilledCapabilities.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullfilledCapabilities);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullfilledCapabilities);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
}
Map<String, ListCapabilityDataDefinition> capabilities = topologyTemplate.getCapabilities();
- if(MapUtils.isNotEmpty(capabilities)) {
- Either<GraphVertex, StorageOperationStatus> associateElementToData =
- associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES,
- EdgeLabelEnum.CAPABILITIES, capabilities);
+ if (MapUtils.isNotEmpty(capabilities)) {
+ Either<GraphVertex, StorageOperationStatus> associateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES,
+ EdgeLabelEnum.CAPABILITIES, capabilities);
if (associateElementToData.isRight()) {
return associateElementToData.right().value();
}
}
return StorageOperationStatus.OK;
-
}
private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
Map<String, MapListRequirementDataDefinition> calculatedRequirements = topologyTemplate.getCalculatedRequirements();
if (calculatedRequirements != null && !calculatedRequirements.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calculatedRequirements);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calculatedRequirements);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
}
Map<String, MapListRequirementDataDefinition> fullfilledRequirements = topologyTemplate.getFullfilledRequirements();
if (fullfilledRequirements != null && !fullfilledRequirements.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullfilledRequirements);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullfilledRequirements);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
}
Map<String, ListRequirementDataDefinition> requirements = topologyTemplate.getRequirements();
- if(MapUtils.isNotEmpty(requirements)) {
- Either<GraphVertex, StorageOperationStatus> associateElementToData =
- associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS,
- EdgeLabelEnum.REQUIREMENTS, requirements);
+ if (MapUtils.isNotEmpty(requirements)) {
+ Either<GraphVertex, StorageOperationStatus> associateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS,
+ EdgeLabelEnum.REQUIREMENTS, requirements);
if (associateElementToData.isRight()) {
return associateElementToData.right().value();
}
@@ -296,38 +290,38 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
private StorageOperationStatus associateTopologyTemplateArtifactsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
Map<String, ArtifactDataDefinition> addInformation = topologyTemplate.getServiceApiArtifacts();
-
if (addInformation != null && !addInformation.isEmpty()) {
addInformation.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
+ String uniqueId = UniqueIdBuilder
+ .buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
a.setUniqueId(uniqueId);
});
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.SERVICE_API_ARTIFACTS, EdgeLabelEnum.SERVICE_API_ARTIFACTS, addInformation);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.SERVICE_API_ARTIFACTS, EdgeLabelEnum.SERVICE_API_ARTIFACTS, addInformation);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
}
Map<String, MapArtifactDataDefinition> instArtifacts = topologyTemplate.getInstDeploymentArtifacts();
-
if (instArtifacts != null && !instArtifacts.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
}
Map<String, MapArtifactDataDefinition> instInfoArtifacts = topologyTemplate.getInstanceArtifacts();
-
if (instInfoArtifacts != null && !instInfoArtifacts.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS, instInfoArtifacts);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS, instInfoArtifacts);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
}
Map<String, ListRequirementDataDefinition> requirements = topologyTemplate.getRequirements();
- if(MapUtils.isNotEmpty(requirements)) {
- Either<GraphVertex, StorageOperationStatus> associateElementToData =
- associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS,
- EdgeLabelEnum.REQUIREMENTS, requirements);
+ if (MapUtils.isNotEmpty(requirements)) {
+ Either<GraphVertex, StorageOperationStatus> associateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS,
+ EdgeLabelEnum.REQUIREMENTS, requirements);
if (associateElementToData.isRight()) {
return associateElementToData.right().value();
}
@@ -336,11 +330,10 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
-
Map<String, AdditionalInfoParameterDataDefinition> addInformation = topologyTemplate.getAdditionalInformation();
-
if (addInformation != null && !addInformation.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformation);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformation);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -363,10 +356,10 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return associateInstGroupsToComponent(nodeTypeVertex, instGroups);
}
-
public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instProps) {
if (instProps != null && !instProps.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_PROPERTIES, EdgeLabelEnum.INST_PROPERTIES, instProps);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.INST_PROPERTIES, EdgeLabelEnum.INST_PROPERTIES, instProps);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -376,7 +369,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
if (instInputs != null && !instInputs.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, instInputs);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_INPUTS,
+ EdgeLabelEnum.INST_INPUTS, instInputs);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -386,7 +380,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, MapGroupsDataDefinition> instGroups) {
if (instGroups != null && !instGroups.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, instGroups);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_GROUPS,
+ EdgeLabelEnum.INST_GROUPS, instGroups);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -394,50 +389,52 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return StorageOperationStatus.OK;
}
-
public StorageOperationStatus deleteInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
-
if (instInputs != null && !instInputs.isEmpty()) {
instInputs.entrySet().forEach(i -> {
List<String> uniqueKeys = new ArrayList<>(i.getValue().getMapToscaDataDefinition().keySet());
List<String> pathKeys = new ArrayList<>();
pathKeys.add(i.getKey());
-
- StorageOperationStatus status = deleteToscaDataDeepElements(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, uniqueKeys, pathKeys, JsonPresentationFields.NAME);
+ StorageOperationStatus status = deleteToscaDataDeepElements(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS,
+ uniqueKeys, pathKeys, JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
return;
}
});
}
-
return StorageOperationStatus.OK;
}
public StorageOperationStatus addInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) {
-
if (instInputs != null && !instInputs.isEmpty()) {
instInputs.entrySet().forEach(i -> {
- StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, i.getValue(), i.getKey());
+ StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_PROPERTIES,
+ VertexTypeEnum.INST_PROPERTIES, i.getValue(), i.getKey());
if (status != StorageOperationStatus.OK) {
return;
}
});
}
-
return StorageOperationStatus.OK;
}
- public StorageOperationStatus associateInstDeploymentArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) {
- return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ public StorageOperationStatus associateInstDeploymentArtifactsToComponent(GraphVertex nodeTypeVertex,
+ Map<String, MapArtifactDataDefinition> instArtifacts) {
+ return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS,
+ EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
}
- public StorageOperationStatus associateInstArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) {
- return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ public StorageOperationStatus associateInstArtifactsToComponent(GraphVertex nodeTypeVertex,
+ Map<String, MapArtifactDataDefinition> instArtifacts) {
+ return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INSTANCE_ARTIFACTS,
+ EdgeLabelEnum.INSTANCE_ARTIFACTS);
}
- private StorageOperationStatus associateInstanceArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instProps, VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel) {
+ private StorageOperationStatus associateInstanceArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instProps,
+ VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel) {
if (instProps != null && !instProps.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, vertexType, edgeLabel, instProps);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, vertexType, edgeLabel,
+ instProps);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -445,58 +442,70 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return StorageOperationStatus.OK;
}
- public StorageOperationStatus associateOrAddCalcCapReqToComponent(GraphVertex nodeTypeVertex, Map<String, MapListRequirementDataDefinition> calcRequirements, Map<String, MapListCapabilityDataDefinition> calcCapabilty, Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) {
+ public StorageOperationStatus associateOrAddCalcCapReqToComponent(GraphVertex nodeTypeVertex,
+ Map<String, MapListRequirementDataDefinition> calcRequirements,
+ Map<String, MapListCapabilityDataDefinition> calcCapabilty,
+ Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) {
if (!MapUtils.isEmpty(calcRequirements)) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calcRequirements);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex,
+ VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calcRequirements);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
Map<String, MapListRequirementDataDefinition> fullFilled = new HashMap<>();
- assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullFilled);
+ assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS,
+ EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullFilled);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
}
if (!MapUtils.isEmpty(calcCapabilty)) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES ,EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex,
+ VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
Map<String, MapListCapabilityDataDefinition> fullFilled = new HashMap<>();
- assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullFilled);
+ assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES,
+ EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullFilled);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
}
- if (!MapUtils.isEmpty(calculatedCapabilitiesProperties)){
- return associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,
- EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapabilitiesProperties)
- .right()
- .on(v -> StorageOperationStatus.OK);
+ if (!MapUtils.isEmpty(calculatedCapabilitiesProperties)) {
+ return associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
+ calculatedCapabilitiesProperties).right().on(v -> StorageOperationStatus.OK);
}
return StorageOperationStatus.OK;
}
- private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> associateOrAddElementToData(GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, T> dataMap){
+ private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> associateOrAddElementToData(GraphVertex nodeTypeVertex,
+ VertexTypeEnum vertexTypeEnum,
+ EdgeLabelEnum edgeLabelEnum,
+ Map<String, T> dataMap) {
return janusGraphDao.getChildVertex(nodeTypeVertex, edgeLabelEnum, JsonParseFlagEnum.ParseJson)
- .either(dataVertex -> addElementsToComponent(nodeTypeVertex, dataVertex, vertexTypeEnum, edgeLabelEnum, dataMap),
- status -> associateElementToDataIfNotFound(status, nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap));
+ .either(dataVertex -> addElementsToComponent(nodeTypeVertex, dataVertex, vertexTypeEnum, edgeLabelEnum, dataMap),
+ status -> associateElementToDataIfNotFound(status, nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap));
}
- private Either<GraphVertex, StorageOperationStatus> associateElementToDataIfNotFound(JanusGraphOperationStatus status, GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, ? extends ToscaDataDefinition> dataMap) {
+ private Either<GraphVertex, StorageOperationStatus> associateElementToDataIfNotFound(JanusGraphOperationStatus status, GraphVertex nodeTypeVertex,
+ VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum,
+ Map<String, ? extends ToscaDataDefinition> dataMap) {
if (status == JanusGraphOperationStatus.NOT_FOUND) {
return associateElementToData(nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap);
}
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
- private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> addElementsToComponent(GraphVertex nodeTypeVertex, GraphVertex dataVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, T> dataMap) {
- Optional<StorageOperationStatus> error = dataMap.entrySet()
- .stream()
- .map(e -> addElementToComponent(nodeTypeVertex.getUniqueId(), vertexTypeEnum, edgeLabelEnum, e))
- .filter(s -> s != StorageOperationStatus.OK)
- .findFirst();
- if(error.isPresent()){
+ private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> addElementsToComponent(GraphVertex nodeTypeVertex,
+ GraphVertex dataVertex,
+ VertexTypeEnum vertexTypeEnum,
+ EdgeLabelEnum edgeLabelEnum,
+ Map<String, T> dataMap) {
+ Optional<StorageOperationStatus> error = dataMap.entrySet().stream()
+ .map(e -> addElementToComponent(nodeTypeVertex.getUniqueId(), vertexTypeEnum, edgeLabelEnum, e))
+ .filter(s -> s != StorageOperationStatus.OK).findFirst();
+ if (error.isPresent()) {
return Either.right(error.get());
}
return Either.left(dataVertex);
@@ -507,9 +516,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return associateInstAttributeToComponent(nodeTypeVertex, instAttr);
}
- public StorageOperationStatus associateForwardingPathToComponent(GraphVertex nodeTypeVertex, Map<String, ForwardingPathDataDefinition> forwardingPathMap) {
+ public StorageOperationStatus associateForwardingPathToComponent(GraphVertex nodeTypeVertex,
+ Map<String, ForwardingPathDataDefinition> forwardingPathMap) {
if (forwardingPathMap != null && !forwardingPathMap.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FORWARDING_PATH, EdgeLabelEnum.FORWARDING_PATH, forwardingPathMap);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.FORWARDING_PATH, EdgeLabelEnum.FORWARDING_PATH, forwardingPathMap);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -519,7 +530,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map<String, MapAttributesDataDefinition> instAttr) {
if (instAttr != null && !instAttr.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -528,13 +540,13 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
public StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, GroupDataDefinition> groups) {
-
if (groups != null && !groups.isEmpty()) {
groups.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName());
p.setUniqueId(uid);
});
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.GROUPS, EdgeLabelEnum.GROUPS, groups);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.GROUPS,
+ EdgeLabelEnum.GROUPS, groups);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -553,9 +565,10 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, Map<String, PropertyDataDefinition> inputs, String id) {
if (inputs != null && !inputs.isEmpty()) {
- inputs.values().stream().filter(e -> e.getUniqueId() == null).forEach(e -> e.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(id, e.getName())));
-
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INPUTS, EdgeLabelEnum.INPUTS, inputs);
+ inputs.values().stream().filter(e -> e.getUniqueId() == null)
+ .forEach(e -> e.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(id, e.getName())));
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INPUTS,
+ EdgeLabelEnum.INPUTS, inputs);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -570,10 +583,9 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
nodeTypeVertex.setJson(topologyTemplate.getCompositions());
}
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.CSAR_UUID, topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, topologyTemplate.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS));
-
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS,
+ topologyTemplate.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS));
return nodeTypeVertex;
-
}
private StorageOperationStatus assosiateMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
@@ -596,7 +608,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
GraphVertex categoryV = category.left().value();
JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(nodeTypeVertex, categoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
if (createEdge != JanusGraphOperationStatus.OK) {
- log.trace("Failed to associate resource {} to category {} with id {}", topologyTemplate.getUniqueId(), categoryName, categoryV.getUniqueId());
+ log.trace("Failed to associate resource {} to category {} with id {}", topologyTemplate.getUniqueId(), categoryName,
+ categoryV.getUniqueId());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
}
return StorageOperationStatus.OK;
@@ -605,21 +618,18 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
@Override
public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) {
JsonParseFlagEnum parseFlag = componentParametersView.detectParseFlag();
-
- Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, parseFlag);
+ Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE,
+ parseFlag);
if (componentByLabelAndId.isRight()) {
return Either.right(componentByLabelAndId.right().value());
}
GraphVertex componentV = componentByLabelAndId.left().value();
-
return getToscaElement(componentV, componentParametersView);
-
}
- // -------------------------------------------------------------
+ // -------------------------------------------------------------
public Either<ToscaElement, StorageOperationStatus> getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) {
TopologyTemplate toscaElement;
-
toscaElement = convertToTopologyTemplate(componentV);
JanusGraphOperationStatus status;
if (!componentParametersView.isIgnoreUsers()) {
@@ -627,7 +637,6 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
status = setLastModifierFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
@@ -637,7 +646,6 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
-
}
}
if (!componentParametersView.isIgnoreArtifacts()) {
@@ -682,126 +690,98 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
-
if (!componentParametersView.isIgnoreGroups()) {
status = setGroupsFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
}
if (!componentParametersView.isIgnorePolicies()) {
status = setPoliciesFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
}
if (!componentParametersView.isIgnoreComponentInstances()) {
status = setInstGroupsFromGraph(componentV, toscaElement);
-
//Mark all CIs that has archived origins
archiveOperation.setArchivedOriginsFlagInComponentInstances(componentV);
-
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
}
if (!componentParametersView.isIgnoreInputs()) {
status = setInputsFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
}
-
if (!componentParametersView.isIgnoreOutputs()) {
final JanusGraphOperationStatus storageStatus = setOutputsFromGraph(componentV, toscaElement);
if (storageStatus != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus));
}
}
-
if (!componentParametersView.isIgnoreProperties()) {
status = setPropertiesFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
}
-
if (!componentParametersView.isIgnoreComponentInstancesInputs()) {
status = setComponentInstancesInputsFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
-
}
}
-
if (!componentParametersView.isIgnoreCapabiltyProperties()) {
status = setComponentInstancesCapPropertiesFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
-
}
}
-
if (!componentParametersView.isIgnoreServicePath()) {
status = setForwardingGraphPropertiesFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
-
}
}
-
if (!componentParametersView.isIgnoreNodeFilter()) {
status = setNodeFilterComponentFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
-
}
}
-
if (!componentParametersView.isIgnoreSubstitutionFilter()) {
status = setSubstitutionFilterComponentFromGraph(componentV, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
-
}
}
-
if (!componentParametersView.isIgnoreInterfaces()) {
JanusGraphOperationStatus storageStatus = setInterfacesFromGraph(componentV, toscaElement);
if (storageStatus != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus));
-
}
}
-
if (!componentParametersView.isIgnoreInterfaces()) {
JanusGraphOperationStatus storageStatus = setInterfcesFromGraph(componentV, toscaElement);
if (storageStatus != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus));
-
}
}
-
if (!componentParametersView.isIgnoreComponentInstancesInterfaces()) {
- JanusGraphOperationStatus storageStatus =
- setComponentInstancesInterfacesFromGraph(componentV, toscaElement);
+ JanusGraphOperationStatus storageStatus = setComponentInstancesInterfacesFromGraph(componentV, toscaElement);
if (storageStatus != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus));
}
}
-
if (!componentParametersView.isIgnoreDataType()) {
JanusGraphOperationStatus storageStatus = setDataTypesFromGraph(componentV, toscaElement);
if (storageStatus != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus));
}
}
-
return Either.left(toscaElement);
}
@@ -853,14 +833,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return JanusGraphOperationStatus.OK;
}
-
- private JanusGraphOperationStatus setComponentInstancesInterfacesFromGraph(GraphVertex componentV,
- TopologyTemplate topologyTemplate) {
- Either<Map<String, MapInterfaceDataDefinition>, JanusGraphOperationStatus> result =
- getDataFromGraph(componentV, EdgeLabelEnum.INST_INTERFACES);
+ private JanusGraphOperationStatus setComponentInstancesInterfacesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
+ Either<Map<String, MapInterfaceDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.INST_INTERFACES);
if (result.isLeft()) {
- result.left().value().entrySet().forEach(entry -> topologyTemplate
- .addComponentInstanceInterfaceMap(entry.getKey(), entry.getValue()));
+ result.left().value().entrySet().forEach(entry -> topologyTemplate.addComponentInstanceInterfaceMap(entry.getKey(), entry.getValue()));
} else {
if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
return result.right().value();
@@ -872,7 +849,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
private StorageOperationStatus associateInterfacesToComponent(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
Map<String, InterfaceDataDefinition> interfaceMap = topologyTemplate.getInterfaces();
if (interfaceMap != null && !interfaceMap.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(topologyTemplateVertex, VertexTypeEnum.INTERFACE, EdgeLabelEnum.INTERFACE, interfaceMap);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(topologyTemplateVertex,
+ VertexTypeEnum.INTERFACE, EdgeLabelEnum.INTERFACE, interfaceMap);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -881,7 +859,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
private JanusGraphOperationStatus setForwardingGraphPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
- Either<Map<String, ForwardingPathDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.FORWARDING_PATH);
+ Either<Map<String, ForwardingPathDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.FORWARDING_PATH);
if (result.isLeft()) {
topologyTemplate.setForwardingPaths(result.left().value());
} else {
@@ -892,9 +871,9 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return JanusGraphOperationStatus.OK;
}
-
private JanusGraphOperationStatus setComponentInstancesCapPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
- Either<Map<String, MapCapabilityProperty>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
+ Either<Map<String, MapCapabilityProperty>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
if (result.isLeft()) {
topologyTemplate.setCalculatedCapabilitiesProperties(result.left().value());
} else {
@@ -902,8 +881,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return result.right().value();
}
}
- Either<Map<String, MapPropertiesDataDefinition>, JanusGraphOperationStatus> capPropResult =
- getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES_PROPERTIES);
+ Either<Map<String, MapPropertiesDataDefinition>, JanusGraphOperationStatus> capPropResult = getDataFromGraph(componentV,
+ EdgeLabelEnum.CAPABILITIES_PROPERTIES);
if (capPropResult.isLeft()) {
topologyTemplate.setCapabilitiesProperties(capPropResult.left().value());
} else {
@@ -911,7 +890,6 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return capPropResult.right().value();
}
}
-
return JanusGraphOperationStatus.OK;
}
@@ -940,7 +918,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
private JanusGraphOperationStatus setComponentInstancesPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
- Either<Map<String, MapPropertiesDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_PROPERTIES);
+ Either<Map<String, MapPropertiesDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.INST_PROPERTIES);
if (result.isLeft()) {
topologyTemplate.setInstProperties(result.left().value());
} else {
@@ -953,8 +932,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
private JanusGraphOperationStatus setComponentInstancesAttributesFromGraph(final GraphVertex componentV,
final TopologyTemplate topologyTemplate) {
- final Either<Map<String, MapAttributesDataDefinition>, JanusGraphOperationStatus> result =
- getDataFromGraph(componentV, EdgeLabelEnum.INST_ATTRIBUTES);
+ final Either<Map<String, MapAttributesDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.INST_ATTRIBUTES);
if (result.isLeft()) {
topologyTemplate.setInstAttributes(result.left().value());
} else if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
@@ -975,11 +954,9 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return JanusGraphOperationStatus.OK;
}
- private JanusGraphOperationStatus setNodeFilterComponentFromGraph(final GraphVertex componentV,
- final TopologyTemplate topologyTemplate) {
-
- final Either<Map<String, CINodeFilterDataDefinition>, JanusGraphOperationStatus> result =
- getDataFromGraph(componentV, EdgeLabelEnum.NODE_FILTER_TEMPLATE);
+ private JanusGraphOperationStatus setNodeFilterComponentFromGraph(final GraphVertex componentV, final TopologyTemplate topologyTemplate) {
+ final Either<Map<String, CINodeFilterDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.NODE_FILTER_TEMPLATE);
if (result.isLeft()) {
topologyTemplate.setNodeFilterComponents(result.left().value());
} else {
@@ -990,11 +967,9 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return JanusGraphOperationStatus.OK;
}
- private JanusGraphOperationStatus setSubstitutionFilterComponentFromGraph(final GraphVertex componentV,
- final TopologyTemplate topologyTemplate) {
-
- final Either<Map<String, SubstitutionFilterDataDefinition>, JanusGraphOperationStatus> result =
- getDataFromGraph(componentV, EdgeLabelEnum.SUBSTITUTION_FILTER_TEMPLATE);
+ private JanusGraphOperationStatus setSubstitutionFilterComponentFromGraph(final GraphVertex componentV, final TopologyTemplate topologyTemplate) {
+ final Either<Map<String, SubstitutionFilterDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.SUBSTITUTION_FILTER_TEMPLATE);
if (result.isLeft()) {
topologyTemplate.setSubstitutionFilterDataDefinitionMap(result.left().value());
} else {
@@ -1005,10 +980,10 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return JanusGraphOperationStatus.OK;
}
-
@Override
protected <T extends ToscaElement> JanusGraphOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) {
- Either<Map<String, MapListRequirementDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
+ Either<Map<String, MapListRequirementDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (result.isLeft()) {
((TopologyTemplate) toscaElement).setCalculatedRequirements(result.left().value());
} else {
@@ -1024,8 +999,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return result.right().value();
}
}
- Either<Map<String, ListRequirementDataDefinition>, JanusGraphOperationStatus> requirementResult =
- getDataFromGraph(componentV, EdgeLabelEnum.REQUIREMENTS);
+ Either<Map<String, ListRequirementDataDefinition>, JanusGraphOperationStatus> requirementResult = getDataFromGraph(componentV,
+ EdgeLabelEnum.REQUIREMENTS);
if (requirementResult.isLeft()) {
toscaElement.setRequirements(requirementResult.left().value());
} else {
@@ -1034,11 +1009,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
}
return JanusGraphOperationStatus.OK;
-
}
protected <T extends ToscaElement> JanusGraphOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) {
- Either<Map<String, MapListCapabilityDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
+ Either<Map<String, MapListCapabilityDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (result.isLeft()) {
((TopologyTemplate) toscaElement).setCalculatedCapabilities(result.left().value());
} else {
@@ -1054,8 +1029,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return result.right().value();
}
}
- Either<Map<String, ListCapabilityDataDefinition>, JanusGraphOperationStatus> capabilitiesResult =
- getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES);
+ Either<Map<String, ListCapabilityDataDefinition>, JanusGraphOperationStatus> capabilitiesResult = getDataFromGraph(componentV,
+ EdgeLabelEnum.CAPABILITIES);
if (capabilitiesResult.isLeft()) {
toscaElement.setCapabilities(capabilitiesResult.left().value());
} else {
@@ -1071,7 +1046,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
if (storageStatus != JanusGraphOperationStatus.OK) {
return storageStatus;
}
- Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.SERVICE_API_ARTIFACTS);
+ Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.SERVICE_API_ARTIFACTS);
if (result.isLeft()) {
toscaElement.setServiceApiArtifacts(result.left().value());
} else {
@@ -1079,7 +1055,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return result.right().value();
}
}
- Either<Map<String, MapArtifactDataDefinition>, JanusGraphOperationStatus> resultInstArt = getDataFromGraph(componentV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ Either<Map<String, MapArtifactDataDefinition>, JanusGraphOperationStatus> resultInstArt = getDataFromGraph(componentV,
+ EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
if (resultInstArt.isLeft()) {
toscaElement.setInstDeploymentArtifacts(resultInstArt.left().value());
} else {
@@ -1087,7 +1064,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return resultInstArt.right().value();
}
}
- Either<Map<String, MapArtifactDataDefinition>, JanusGraphOperationStatus> instanceArt = getDataFromGraph(componentV, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ Either<Map<String, MapArtifactDataDefinition>, JanusGraphOperationStatus> instanceArt = getDataFromGraph(componentV,
+ EdgeLabelEnum.INSTANCE_ARTIFACTS);
if (instanceArt.isLeft()) {
toscaElement.setInstanceArtifacts(instanceArt.left().value());
} else {
@@ -1107,8 +1085,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return result.right().value();
}
}
- Either<Map<String, ListCapabilityDataDefinition>, JanusGraphOperationStatus> capabilitiesResult =
- getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES);
+ Either<Map<String, ListCapabilityDataDefinition>, JanusGraphOperationStatus> capabilitiesResult = getDataFromGraph(componentV,
+ EdgeLabelEnum.CAPABILITIES);
if (capabilitiesResult.isLeft()) {
toscaElement.setCapabilities(capabilitiesResult.left().value());
} else {
@@ -1119,10 +1097,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return JanusGraphOperationStatus.OK;
}
- private JanusGraphOperationStatus setOutputsFromGraph(final GraphVertex componentV,
- final TopologyTemplate toscaElement) {
- final Either<Map<String, AttributeDataDefinition>, JanusGraphOperationStatus> result =
- getDataFromGraph(componentV, EdgeLabelEnum.OUTPUTS);
+ private JanusGraphOperationStatus setOutputsFromGraph(final GraphVertex componentV, final TopologyTemplate toscaElement) {
+ final Either<Map<String, AttributeDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.OUTPUTS);
if (result.isLeft()) {
toscaElement.setOutputs(result.left().value());
} else {
@@ -1147,24 +1123,25 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
private JanusGraphOperationStatus setTopologyTempalteCategoriesFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
List<CategoryDefinition> categories = new ArrayList<>();
-
switch (componentV.getType()) {
- case RESOURCE:
- return setResourceCategoryFromGraph(componentV, toscaElement);
- case SERVICE:
- return setServiceCategoryFromGraph(componentV, toscaElement, categories);
-
- default:
- log.debug("Not supported component type {} ", componentV.getType());
- break;
+ case RESOURCE:
+ return setResourceCategoryFromGraph(componentV, toscaElement);
+ case SERVICE:
+ return setServiceCategoryFromGraph(componentV, toscaElement, categories);
+ default:
+ log.debug("Not supported component type {} ", componentV.getType());
+ break;
}
return JanusGraphOperationStatus.OK;
}
- private JanusGraphOperationStatus setServiceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement, List<CategoryDefinition> categories) {
- Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
+ private JanusGraphOperationStatus setServiceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement,
+ List<CategoryDefinition> categories) {
+ Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
+ .getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
- log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value());
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(),
+ childVertex.right().value());
return childVertex.right().value();
}
GraphVertex categoryV = childVertex.left().value();
@@ -1173,31 +1150,29 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
category.setUniqueId(categoryV.getUniqueId());
category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
- final Boolean useServiceSubstitutionForNestedServices = (Boolean)metadataProperties.get(GraphPropertyEnum.USE_SUBSTITUTION_FOR_NESTED_SERVICES);
- category.setUseServiceSubstitutionForNestedServices(useServiceSubstitutionForNestedServices == null ? false : useServiceSubstitutionForNestedServices);
-
- Type listTypeCat = new TypeToken<List<String>>() {}.getType();
+ final Boolean useServiceSubstitutionForNestedServices = (Boolean) metadataProperties
+ .get(GraphPropertyEnum.USE_SUBSTITUTION_FOR_NESTED_SERVICES);
+ category.setUseServiceSubstitutionForNestedServices(
+ useServiceSubstitutionForNestedServices == null ? false : useServiceSubstitutionForNestedServices);
+ Type listTypeCat = new TypeToken<List<String>>() {
+ }.getType();
List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS.getProperty()), listTypeCat);
category.setIcons(iconsfromJsonCat);
-
- final Type metadataKeysTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {}.getType();
- final List<MetadataKeyDataDefinition> metadataKeysfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.METADATA_KEYS), metadataKeysTypeCat);
+ final Type metadataKeysTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
+ }.getType();
+ final List<MetadataKeyDataDefinition> metadataKeysfromJsonCat = getGson()
+ .fromJson((String) metadataProperties.get(GraphPropertyEnum.METADATA_KEYS), metadataKeysTypeCat);
category.setMetadataKeys(metadataKeysfromJsonCat);
-
categories.add(category);
toscaElement.setCategories(categories);
-
return JanusGraphOperationStatus.OK;
}
@SuppressWarnings("unchecked")
private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) {
-
TopologyTemplate topologyTemplate = super.convertToComponent(componentV);
-
Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) componentV.getJson();
topologyTemplate.setCompositions(json);
-
return topologyTemplate;
}
@@ -1222,13 +1197,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
log.debug("Failed to disassociate instances properties for {} error {}", toscaElementVertex.getUniqueId(), status);
Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disassociate instances inputs for {} error {}", toscaElementVertex.getUniqueId(), status);
Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.GROUPS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disassociate groups for {} error {}", toscaElementVertex.getUniqueId(), status);
@@ -1309,19 +1282,14 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
log.debug("Failed to disassociate instance artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
- status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT,
- EdgeLabelEnum.REQUIREMENTS);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
if (status != JanusGraphOperationStatus.OK) {
- log.debug("Failed to disassociate requirements for {} error {}",
- toscaElementVertex.getUniqueId(), status);
+ log.debug("Failed to disassociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
- status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT,
- EdgeLabelEnum.CAPABILITIES);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
if (status != JanusGraphOperationStatus.OK) {
- log.debug("Failed to disassociate capabilities for {} error {}",
- toscaElementVertex.getUniqueId(), status);
+ log.debug("Failed to disassociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INTERFACES);
@@ -1331,7 +1299,6 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
toscaElementVertex.getVertex().remove();
log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId());
-
return nodeType;
}
@@ -1349,6 +1316,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
@Override
protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) {
// Product isn't supported now!!
+
// TODO add for Product
if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.SERVICE) {
return validateServiceCategory(toscaElementToUpdate, elementV);
@@ -1373,22 +1341,21 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
StorageOperationStatus status = StorageOperationStatus.OK;
List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories();
CategoryDefinition newCategory = newCategoryList.get(0);
-
- Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
+ .getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
- log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value());
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(),
+ childVertex.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value());
}
-
GraphVertex categoryV = childVertex.left().value();
Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
-
String newCategoryName = newCategory.getName();
if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) {
// the category was changed
- Either<GraphVertex, StorageOperationStatus> getCategoryVertex = categoryOperation.getCategory(newCategoryName, VertexTypeEnum.SERVICE_CATEGORY);
-
+ Either<GraphVertex, StorageOperationStatus> getCategoryVertex = categoryOperation
+ .getCategory(newCategoryName, VertexTypeEnum.SERVICE_CATEGORY);
if (getCategoryVertex.isRight()) {
return getCategoryVertex.right().value();
}
@@ -1399,8 +1366,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return status;
}
- public Either<GraphVertex, StorageOperationStatus> updateDistributionStatus(String uniqueId, User user, DistributionStatusEnum distributionStatus) {
-
+ public Either<GraphVertex, StorageOperationStatus> updateDistributionStatus(String uniqueId, User user,
+ DistributionStatusEnum distributionStatus) {
Either<GraphVertex, StorageOperationStatus> result = null;
String userId = user.getUserId();
Either<GraphVertex, JanusGraphOperationStatus> getRes = findUserVertex(userId);
@@ -1416,7 +1383,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
getRes = janusGraphDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata);
if (getRes.isRight()) {
JanusGraphOperationStatus status = getRes.right().value();
- log.debug( "Cannot find service {} in the graph. status is {}", uniqueId, status);
+ log.debug("Cannot find service {} in the graph. status is {}", uniqueId, status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
@@ -1424,14 +1391,17 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
serviceVertex = getRes.left().value();
Iterator<Edge> edgeIterator = serviceVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER.name());
if (edgeIterator.hasNext()) {
- log.debug("Remove existing edge from user to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
+ log.debug("Remove existing edge from user to component {}. Edge type is {}", userId, uniqueId,
+ EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
edgeIterator.next().remove();
}
}
if (result == null) {
- JanusGraphOperationStatus status = janusGraphDao.createEdge(userVertex, serviceVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null);
+ JanusGraphOperationStatus status = janusGraphDao
+ .createEdge(userVertex, serviceVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null);
if (status != JanusGraphOperationStatus.OK) {
- log.debug( "Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
+ log.debug("Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId,
+ EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
@@ -1449,8 +1419,10 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
return result;
}
+
/**
* Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
+ *
* @param componentId
* @param instanceId
* @param capabilityName
@@ -1458,53 +1430,59 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
* @param ownerId
* @return
*/
- public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
-
+ public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId,
+ String instanceId,
+ String capabilityName,
+ String capabilityType,
+ String ownerId) {
Either<List<ComponentInstanceProperty>, StorageOperationStatus> result = null;
Map<String, MapCapabilityProperty> mapPropertiesDataDefinition = null;
- Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(componentId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(componentId,
+ ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.NoParse);
if (componentByLabelAndId.isRight()) {
result = Either.right(componentByLabelAndId.right().value());
}
- if(componentByLabelAndId.isLeft()){
- Either<Map<String, MapCapabilityProperty>, JanusGraphOperationStatus> getDataRes = getDataFromGraph(componentByLabelAndId.left().value(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
+ if (componentByLabelAndId.isLeft()) {
+ Either<Map<String, MapCapabilityProperty>, JanusGraphOperationStatus> getDataRes = getDataFromGraph(componentByLabelAndId.left().value(),
+ EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
if (getDataRes.isRight()) {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getDataRes.right().value()));
} else {
mapPropertiesDataDefinition = getDataRes.left().value();
}
}
- if(isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)){
- result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()));
+ if (isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)) {
+ result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId,
+ mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()));
}
return result;
}
- public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceId, MapCapabilityProperty instanceProperties) {
- return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instanceProperties, componentInstanceId);
+ public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceId,
+ MapCapabilityProperty instanceProperties) {
+ return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
+ instanceProperties, componentInstanceId);
}
- public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent,
- String componentInstanceId,
+ public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceId,
MapInterfaceDataDefinition instanceInterfaces) {
if (MapUtils.isNotEmpty(instanceInterfaces.getMapToscaDataDefinition())) {
- return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(),
- EdgeLabelEnum.INST_INTERFACES, instanceInterfaces, componentInstanceId);
+ return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INTERFACES, instanceInterfaces,
+ componentInstanceId);
}
return StorageOperationStatus.OK;
}
-
private boolean isNotEmptyMapOfProperties(String instanceId, Map<String, MapCapabilityProperty> mapPropertiesDataDefinition) {
- return MapUtils.isNotEmpty(mapPropertiesDataDefinition) &&
- instanceId != null &&
- mapPropertiesDataDefinition.get(instanceId) != null &&
- MapUtils.isNotEmpty(mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition());
+ return MapUtils.isNotEmpty(mapPropertiesDataDefinition) && instanceId != null && mapPropertiesDataDefinition.get(instanceId) != null
+ && MapUtils.isNotEmpty(mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition());
}
- private List<ComponentInstanceProperty> findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType, String ownerId, Map<String, MapPropertiesDataDefinition> propertiesMap) {
+ private List<ComponentInstanceProperty> findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType,
+ String ownerId,
+ Map<String, MapPropertiesDataDefinition> propertiesMap) {
List<ComponentInstanceProperty> capPropsList = null;
- for(Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()){
+ for (Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()) {
if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, ownerId, capProp)) {
Map<String, PropertyDataDefinition> capMap = capProp.getValue().getMapToscaDataDefinition();
if (capMap != null && !capMap.isEmpty()) {
@@ -1513,27 +1491,30 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
}
}
- if(capPropsList == null){
+ if (capPropsList == null) {
capPropsList = new ArrayList<>();
}
return capPropsList;
}
- private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, String ownerId, Entry<String, MapPropertiesDataDefinition> capProp) {
+ private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, String ownerId,
+ Entry<String, MapPropertiesDataDefinition> capProp) {
if (capProp != null) {
- String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM );
+ String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM);
if (path.length < 4) {
log.debug("wrong key format for capabilty, key {}", capProp);
return false;
}
- return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[1].equals(ownerId) && path[0].equals(instanceId);
+ return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[1].equals(ownerId) && path[0]
+ .equals(instanceId);
}
return false;
}
public StorageOperationStatus addPolicyToToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
fillPolicyDefinition(componentV, policyDefinition, counter);
- return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID);
+ return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition,
+ JsonPresentationFields.UNIQUE_ID);
}
public StorageOperationStatus addPoliciesToToscaElement(GraphVertex componentV, List<PolicyDefinition> policies) {
@@ -1541,23 +1522,27 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
public StorageOperationStatus updatePolicyOfToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition) {
- return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID);
+ return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition,
+ JsonPresentationFields.UNIQUE_ID);
}
public StorageOperationStatus updatePoliciesOfToscaElement(GraphVertex componentV, List<PolicyDefinition> policiesDefinitions) {
- return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policiesDefinitions, JsonPresentationFields.UNIQUE_ID);
+ return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policiesDefinitions,
+ JsonPresentationFields.UNIQUE_ID);
}
public StorageOperationStatus removePolicyFromToscaElement(GraphVertex componentV, String policyId) {
- return deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID);
+ return deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID);
}
public StorageOperationStatus updateGroupOfToscaElement(GraphVertex componentV, GroupDefinition groupDefinition) {
- return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, JsonPresentationFields.CI_INVARIANT_NAME);
+ return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition,
+ JsonPresentationFields.CI_INVARIANT_NAME);
}
private void fillPolicyDefinition(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
- String policyName = buildSubComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME), policyDefinition.getPolicyTypeName(), counter);
+ String policyName = buildSubComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME),
+ policyDefinition.getPolicyTypeName(), counter);
policyDefinition.setName(policyName);
policyDefinition.setInvariantName(policyName);
policyDefinition.setComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME));
@@ -1566,43 +1551,50 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
policyDefinition.setPolicyUUID(UniqueIdBuilder.generateUUID());
}
- public static String buildSubComponentName(String componentName, String subComponentTypeName, int counter) {
- String normalizedComponentName = ValidationUtils.normalizeComponentInstanceName(componentName);
- String typeSuffix = subComponentTypeName.substring(subComponentTypeName.lastIndexOf('.') + 1, subComponentTypeName.length());
- return normalizedComponentName + Constants.GROUP_POLICY_NAME_DELIMETER + typeSuffix + Constants.GROUP_POLICY_NAME_DELIMETER + counter;
- }
-
void revertNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) {
- if(MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())){
- GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
- .left()
- .on(this::throwStorageException);
- if(MapUtils.isNotEmpty(toscaElement.getComponentInstances())){
- toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver.revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), this::getOriginToscaElement));
+ if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) {
+ GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).left().on(this::throwStorageException);
+ if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) {
+ toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver
+ .revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), this::getOriginToscaElement));
}
- if(MapUtils.isNotEmpty(toscaElement.getGroups())){
- toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver.revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), this::getOriginToscaElement));
+ if (MapUtils.isNotEmpty(toscaElement.getGroups())) {
+ toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver
+ .revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), this::getOriginToscaElement));
}
- topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities());
- topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements());
- topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties());
+ topologyTemplateOperation
+ .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES,
+ toscaElement.getCalculatedCapabilities());
+ topologyTemplateOperation
+ .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS,
+ toscaElement.getCalculatedRequirements());
+ topologyTemplateOperation
+ .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,
+ toscaElement.getCalculatedCapabilitiesProperties());
}
}
public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) {
- if(MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())){
- GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
- .left()
- .on(this::throwStorageException);
- if(MapUtils.isNotEmpty(toscaElement.getComponentInstances())){
- toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), i.getNormalizedName(), this::getOriginToscaElement));
+ if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) {
+ GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).left().on(this::throwStorageException);
+ if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) {
+ toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver
+ .updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), i.getNormalizedName(),
+ this::getOriginToscaElement));
}
- if(MapUtils.isNotEmpty(toscaElement.getGroups())){
- toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), g.getName(), this::getOriginToscaElement));
+ if (MapUtils.isNotEmpty(toscaElement.getGroups())) {
+ toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver
+ .updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), g.getName(), this::getOriginToscaElement));
}
- topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities());
- topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements());
- topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties());
+ topologyTemplateOperation
+ .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES,
+ toscaElement.getCalculatedCapabilities());
+ topologyTemplateOperation
+ .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS,
+ toscaElement.getCalculatedRequirements());
+ topologyTemplateOperation
+ .updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES,
+ toscaElement.getCalculatedCapabilitiesProperties());
}
}
@@ -1610,13 +1602,12 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
log.debug("#getOriginToscaElement - origin name: {}", instance.getComponentName());
ToscaElementTypeEnum elementType = detectToscaType(instance.getOriginType());
Either<ToscaElement, StorageOperationStatus> getOriginRes;
- if(elementType == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE){
+ if (elementType == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE) {
getOriginRes = this.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter());
-
} else {
getOriginRes = nodeTypeOperation.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter());
}
- if(getOriginRes.isRight()){
+ if (getOriginRes.isRight()) {
log.debug("Failed to get an origin component with uniqueId {}", CapabilityRequirementNameResolver.getActualComponentUid(instance));
throw new StorageException(getOriginRes.right().value());
}
@@ -1625,11 +1616,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
private ToscaElementTypeEnum detectToscaType(OriginTypeEnum originType) {
log.debug("#detectToscaType - type: {}", originType);
- if(originType == OriginTypeEnum.VFC
- || originType == OriginTypeEnum.CP
- || originType == OriginTypeEnum.VL
- || originType == OriginTypeEnum.Configuration
- || originType == OriginTypeEnum.VFCMT){
+ if (originType == OriginTypeEnum.VFC || originType == OriginTypeEnum.CP || originType == OriginTypeEnum.VL
+ || originType == OriginTypeEnum.Configuration || originType == OriginTypeEnum.VFCMT) {
return ToscaElementTypeEnum.NODE_TYPE;
} else {
return ToscaElementTypeEnum.TOPOLOGY_TEMPLATE;
@@ -1643,43 +1631,38 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
filter.setIgnoreRequirements(false);
return filter;
}
+
public void updateCapReqPropertiesOwnerId(String componentId, TopologyTemplate toscaElement) {
- GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
- .left().on(this::throwStorageException);
+ GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).left().on(this::throwStorageException);
updateCapOwnerId(toscaElement, componentId);
updateReqOwnerId(toscaElement, componentId);
updatePropertiesOwnerId(toscaElement, componentId);
topologyTemplateOperation
-
- .updateFullToscaData(toscaElementV, EdgeLabelEnum.CAPABILITIES,
- VertexTypeEnum.CAPABILITIES, toscaElement.getCapabilities());
+ .updateFullToscaData(toscaElementV, EdgeLabelEnum.CAPABILITIES, VertexTypeEnum.CAPABILITIES, toscaElement.getCapabilities());
topologyTemplateOperation
- .updateFullToscaData(toscaElementV, EdgeLabelEnum.REQUIREMENTS,
- VertexTypeEnum.REQUIREMENTS, toscaElement.getRequirements());
+ .updateFullToscaData(toscaElementV, EdgeLabelEnum.REQUIREMENTS, VertexTypeEnum.REQUIREMENTS, toscaElement.getRequirements());
topologyTemplateOperation
- .updateFullToscaData(toscaElementV, EdgeLabelEnum.PROPERTIES,
- VertexTypeEnum.PROPERTIES, toscaElement.getProperties());
+ .updateFullToscaData(toscaElementV, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, toscaElement.getProperties());
}
private void updateCapOwnerId(ToscaElement toscaElement, String ownerId) {
- if(MapUtils.isNotEmpty(toscaElement.getCapabilities())) {
+ if (MapUtils.isNotEmpty(toscaElement.getCapabilities())) {
toscaElement.getCapabilities().values().stream().flatMap(listCapDef -> listCapDef.getListToscaDataDefinition().stream())
- .forEach(capabilityDefinition -> capabilityDefinition.setOwnerId(ownerId));
+ .forEach(capabilityDefinition -> capabilityDefinition.setOwnerId(ownerId));
}
}
private void updateReqOwnerId(ToscaElement toscaElement, String ownerId) {
- if(MapUtils.isNotEmpty(toscaElement.getRequirements())) {
+ if (MapUtils.isNotEmpty(toscaElement.getRequirements())) {
toscaElement.getRequirements().values().stream().flatMap(listReqDef -> listReqDef.getListToscaDataDefinition().stream())
- .forEach(requirementDefinition -> requirementDefinition.setOwnerId(ownerId));
+ .forEach(requirementDefinition -> requirementDefinition.setOwnerId(ownerId));
}
}
private void updatePropertiesOwnerId(ToscaElement toscaElement, String ownerId) {
Map<String, PropertyDataDefinition> properties = toscaElement.getProperties();
- if(MapUtils.isNotEmpty(properties)) {
+ if (MapUtils.isNotEmpty(properties)) {
properties.values().forEach(propertyDataDefinition -> propertyDataDefinition.setParentUniqueId(ownerId));
}
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaDataOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaDataOperation.java
index 1501b79ca5..10752594b9 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaDataOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaDataOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.jsonjanusgraph.operations;
@org.springframework.stereotype.Component("tosca-data-operation")
public class ToscaDataOperation extends BaseOperation {
+
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java
index a2b1f89667..a2dd8eb966 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import static fj.P.p;
import fj.P2;
-import org.janusgraph.core.JanusGraphVertex;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
@@ -32,6 +38,7 @@ import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.janusgraph.core.JanusGraphVertex;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
@@ -41,7 +48,15 @@ import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils;
import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
-import org.openecomp.sdc.be.datatypes.elements.*;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
@@ -61,92 +76,76 @@ import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.*;
-import java.util.stream.Collectors;
-
@org.springframework.stereotype.Component("tosca-element-lifecycle-operation")
-
/**
* Allows to perform lifecycle operations: checkin, checkout, submit for testing, start certification and certification process for tosca element
*/
public class ToscaElementLifecycleOperation extends BaseOperation {
- private static final String FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS = "Failed to delete last state edge. Status is {}. ";
- private static final String FAILED_TO_GET_VERTICES = "Failed to get vertices by id {}. Status is {}. ";
public static final String VERSION_DELIMITER = ".";
public static final String VERSION_DELIMITER_REGEXP = "\\.";
-
+ private static final String FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS = "Failed to delete last state edge. Status is {}. ";
+ private static final String FAILED_TO_GET_VERTICES = "Failed to get vertices by id {}. Status is {}. ";
private static final Logger log = Logger.getLogger(ToscaElementLifecycleOperation.class);
+ static StorageOperationStatus handleFailureToPrepareParameters(final JanusGraphOperationStatus status, final String toscaElementId) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
+ return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
+ }
+
+ static Either<ToscaElement, StorageOperationStatus> getToscaElementFromOperation(final ToscaElementOperation operation, final String uniqueId,
+ final String toscaElementId) {
+ return operation.getToscaElement(uniqueId).right().map(status -> {
+ //We log a potential error we got while retrieving the ToscaElement
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated tosca element {}. Status is {}", toscaElementId, status);
+ return status;
+ });
+ }
+
+ private static StorageOperationStatus logDebugMessageAndReturnStorageOperationStatus(final StorageOperationStatus status, final String msg,
+ final Object... args) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, msg, args);
+ return status;
+ }
+
/**
* Performs changing a lifecycle state of tosca element from "checked out" or "ready for certification" to "checked in"
- *
+ *
* @param currState
* @param toscaElementId
* @param modifierId
* @param ownerId
* @return
*/
- public Either<ToscaElement, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState,
- String toscaElementId, String modifierId, String ownerId) {
+ public Either<ToscaElement, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, String toscaElementId, String modifierId,
+ String ownerId) {
try {
- return janusGraphDao
- .getVerticesByUniqueIdAndParseFlag(
- prepareParametersToGetVerticesForCheckin(toscaElementId, modifierId, ownerId))
- .right().map(status -> handleFailureToPrepareParameters(status, toscaElementId))
- .left().bind(
- verticesMap ->
- checkinToscaELement(
- currState,
- verticesMap.get(toscaElementId),
- verticesMap.get(ownerId),
- verticesMap.get(modifierId),
- LifecycleStateEnum.NOT_CERTIFIED_CHECKIN
- ).left().bind(checkinResult -> {
- //We retrieve the operation
- ToscaElementOperation operation =
- getToscaElementOperation(verticesMap.get(toscaElementId).getLabel());
-
- //We retrieve the ToscaElement from the operation
- return getToscaElementFromOperation(operation, checkinResult.getUniqueId(), toscaElementId);
- })
- );
+ return janusGraphDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckin(toscaElementId, modifierId, ownerId))
+ .right().map(status -> handleFailureToPrepareParameters(status, toscaElementId)).left().bind(
+ verticesMap -> checkinToscaELement(currState, verticesMap.get(toscaElementId), verticesMap.get(ownerId),
+ verticesMap.get(modifierId), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN).left().bind(checkinResult -> {
+ //We retrieve the operation
+ ToscaElementOperation operation = getToscaElementOperation(verticesMap.get(toscaElementId).getLabel());
+ //We retrieve the ToscaElement from the operation
+ return getToscaElementFromOperation(operation, checkinResult.getUniqueId(), toscaElementId);
+ }));
} catch (Exception e) {
- CommonUtility.addRecordToLog(
- log, LogLevelEnum.DEBUG, "Exception occurred during checkin of tosca element {}. {} ", toscaElementId,
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occurred during checkin of tosca element {}. {} ", toscaElementId,
e.getMessage());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
}
- static StorageOperationStatus handleFailureToPrepareParameters(final JanusGraphOperationStatus status, final String toscaElementId) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
- return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
- }
-
- static Either<ToscaElement, StorageOperationStatus> getToscaElementFromOperation(final ToscaElementOperation operation,
- final String uniqueId, final String toscaElementId) {
- return operation.getToscaElement(uniqueId)
- .right().map(status -> {
- //We log a potential error we got while retrieving the ToscaElement
- CommonUtility
- .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated tosca element {}. Status is {}",
- toscaElementId, status);
- return status;
- });
- }
-
/**
* Returns vertex presenting owner of tosca element specified by uniqueId
- *
+ *
* @param toscaElementId
* @return
*/
public Either<User, StorageOperationStatus> getToscaElementOwner(String toscaElementId) {
Either<User, StorageOperationStatus> result = null;
GraphVertex toscaElement = null;
- Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes = janusGraphDao
- .getVertexById(toscaElementId, JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes = janusGraphDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse);
if (getToscaElementRes.isRight()) {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getToscaElementRes.right().value()));
}
@@ -164,7 +163,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
/**
* Returns vertex presenting owner of tosca element specified by uniqueId
- *
+ *
* @param toscaElement
* @return
*/
@@ -179,7 +178,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
/**
* Performs checkout of a tosca element
- *
+ *
* @param toscaElementId
* @param modifierId
* @param ownerId
@@ -207,60 +206,53 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
if (result == null) {
result = cloneToscaElementForCheckout(vertices.get(toscaElementId), vertices.get(modifierId));
if (result.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to checkout tosca element {}. Status is {} ", toscaElementId, result.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to checkout tosca element {}. Status is {} ", toscaElementId,
+ result.right().value());
}
-
}
} catch (Exception e) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during checkout tosca element {}. {}", toscaElementId, e.getMessage());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during checkout tosca element {}. {}", toscaElementId, e.getMessage());
}
return result;
}
/**
* Performs undo checkout for tosca element
- *
+ *
* @param toscaElementId
* @return
*/
public Either<ToscaElement, StorageOperationStatus> undoCheckout(String toscaElementId) {
try {
- return janusGraphDao.getVertexById(toscaElementId, JsonParseFlagEnum.ParseMetadata)
- .right().map(errorStatus -> {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
- return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(errorStatus);
- })
- .left().bind(this::retrieveAndUpdatePreviousVersion)
- .left().bind(this::updateEdgeToCatalogRootAndReturnPreVersionElement);
+ return janusGraphDao.getVertexById(toscaElementId, JsonParseFlagEnum.ParseMetadata).right().map(errorStatus -> {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
+ return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(errorStatus);
+ }).left().bind(this::retrieveAndUpdatePreviousVersion).left().bind(this::updateEdgeToCatalogRootAndReturnPreVersionElement);
} catch (Exception e) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occurred during undo checkout tosca element {}. {}", toscaElementId, e.getMessage());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occurred during undo checkout tosca element {}. {}", toscaElementId,
+ e.getMessage());
return null;
}
}
- private Either<P2<GraphVertex, JanusGraphVertex>, StorageOperationStatus> retrieveAndUpdatePreviousVersion(
- final GraphVertex currVersionV) {
+ private Either<P2<GraphVertex, JanusGraphVertex>, StorageOperationStatus> retrieveAndUpdatePreviousVersion(final GraphVertex currVersionV) {
if (!hasPreviousVersion(currVersionV)) {
return Either.left(p(currVersionV, null));
} else {
// find previous version
- Iterator<Edge> nextVersionComponentIter = currVersionV.getVertex()
- .edges(Direction.IN, EdgeLabelEnum.VERSION.name());
-
+ Iterator<Edge> nextVersionComponentIter = currVersionV.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name());
if (nextVersionComponentIter == null || !nextVersionComponentIter.hasNext()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
- "Failed to fetch previous version of tosca element with name {}. ",
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ",
currVersionV.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString());
return Either.right(StorageOperationStatus.NOT_FOUND);
} else {
Vertex preVersionVertex = nextVersionComponentIter.next().outVertex();
- StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(
- preVersionVertex);
+ StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(preVersionVertex);
if (updateOldResourceResult != StorageOperationStatus.OK) {
return Either.right(updateOldResourceResult);
} else {
P2<GraphVertex, JanusGraphVertex> result = p(currVersionV, (JanusGraphVertex) preVersionVertex);
-
return Either.left(result);
}
}
@@ -269,30 +261,23 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
private Either<ToscaElement, StorageOperationStatus> updateEdgeToCatalogRootAndReturnPreVersionElement(
final P2<GraphVertex, JanusGraphVertex> tuple) {
-
final GraphVertex currVersionV = tuple._1();
final JanusGraphVertex preVersionVertex = tuple._2();
-
StorageOperationStatus updateCatalogRes = updateEdgeToCatalogRootByUndoCheckout(preVersionVertex, currVersionV);
if (updateCatalogRes != StorageOperationStatus.OK) {
return Either.right(updateCatalogRes);
} else {
final ToscaElementOperation operation = getToscaElementOperation(currVersionV.getLabel());
-
- return operation.deleteToscaElement(currVersionV)
- .left().bind(discarded -> getUpdatedPreVersionElement(operation, preVersionVertex));
+ return operation.deleteToscaElement(currVersionV).left().bind(discarded -> getUpdatedPreVersionElement(operation, preVersionVertex));
}
}
- private Either<ToscaElement, StorageOperationStatus> getUpdatedPreVersionElement(
- final ToscaElementOperation operation,
- final JanusGraphVertex preVersionVertex) {
-
+ private Either<ToscaElement, StorageOperationStatus> getUpdatedPreVersionElement(final ToscaElementOperation operation,
+ final JanusGraphVertex preVersionVertex) {
if (preVersionVertex == null) {
return Either.left(null);
} else {
- String uniqueIdPreVer = (String) janusGraphDao
- .getProperty(preVersionVertex, GraphPropertyEnum.UNIQUE_ID.getProperty());
+ String uniqueIdPreVer = (String) janusGraphDao.getProperty(preVersionVertex, GraphPropertyEnum.UNIQUE_ID.getProperty());
return operation.getToscaElement(uniqueIdPreVer);
}
}
@@ -300,99 +285,65 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
private boolean hasPreviousVersion(GraphVertex toscaElementVertex) {
boolean hasPreviousVersion = true;
String version = (String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION);
- if (StringUtils.isEmpty(version) || "0.1".equals(version))
+ if (StringUtils.isEmpty(version) || "0.1".equals(version)) {
hasPreviousVersion = false;
+ }
return hasPreviousVersion;
}
- public Either<ToscaElement, StorageOperationStatus> certifyToscaElement(
- String toscaElementId,
- String modifierId,
- String ownerId) {
+ public Either<ToscaElement, StorageOperationStatus> certifyToscaElement(String toscaElementId, String modifierId, String ownerId) {
try {
return janusGraphDao
- .getVerticesByUniqueIdAndParseFlag(
- prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId))
- .right().map(status ->
- logDebugMessageAndReturnStorageOperationStatus(
- DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status),
- FAILED_TO_GET_VERTICES,
- toscaElementId))
- .left().bind(verticesRes -> {
+ .getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)).right()
+ .map(status -> logDebugMessageAndReturnStorageOperationStatus(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status),
+ FAILED_TO_GET_VERTICES, toscaElementId)).left().bind(verticesRes -> {
GraphVertex toscaElement = verticesRes.get(toscaElementId);
GraphVertex modifier = verticesRes.get(modifierId);
- Integer majorVersion = getMajorVersion(
- (String) toscaElement.getMetadataProperty(GraphPropertyEnum.VERSION));
-
- return handleRelationsBeforeCertifyingAndProcessClone(toscaElement,
- modifier, majorVersion);
+ Integer majorVersion = getMajorVersion((String) toscaElement.getMetadataProperty(GraphPropertyEnum.VERSION));
+ return handleRelationsBeforeCertifyingAndProcessClone(toscaElement, modifier, majorVersion);
});
} catch (Exception e) {
- return Either.right(
- logDebugMessageAndReturnStorageOperationStatus(StorageOperationStatus.GENERAL_ERROR,
- "Exception occurred during certification tosca element {}.",
- toscaElementId, e)
- );
+ return Either.right(logDebugMessageAndReturnStorageOperationStatus(StorageOperationStatus.GENERAL_ERROR,
+ "Exception occurred during certification tosca element {}.", toscaElementId, e));
}
}
- private Either<ToscaElement, StorageOperationStatus> handleRelationsBeforeCertifyingAndProcessClone(
- GraphVertex toscaElement,
- GraphVertex modifier,
- Integer majorVersion) {
- StorageOperationStatus status = handleRelationsOfPreviousToscaElementBeforeCertifying(toscaElement,
- modifier, majorVersion);
+ private Either<ToscaElement, StorageOperationStatus> handleRelationsBeforeCertifyingAndProcessClone(GraphVertex toscaElement,
+ GraphVertex modifier, Integer majorVersion) {
+ StorageOperationStatus status = handleRelationsOfPreviousToscaElementBeforeCertifying(toscaElement, modifier, majorVersion);
if (status != StorageOperationStatus.OK) {
- return Either.right(
- logDebugMessageAndReturnStorageOperationStatus(status,
- "Failed to handle relations of previous tosca element before certifying {}. Status is {}. ",
- toscaElement.getUniqueId(), status));
+ return Either.right(logDebugMessageAndReturnStorageOperationStatus(status,
+ "Failed to handle relations of previous tosca element before certifying {}. Status is {}. ", toscaElement.getUniqueId(), status));
} else {
return cloneToscaElementAndHandleRelations(toscaElement, modifier, majorVersion);
}
}
- private Either<ToscaElement, StorageOperationStatus> cloneToscaElementAndHandleRelations(
- GraphVertex toscaElement,
- GraphVertex modifier,
- Integer majorVersion) {
- return cloneToscaElementForCertify(toscaElement, modifier, majorVersion)
- .right().map(status -> logDebugMessageAndReturnStorageOperationStatus(status,
- "Failed to clone tosca element during certification. "))
- .left().bind(certifiedToscaElement ->
- handleRelationsOfNewestCertifiedToscaElementAndReturn(toscaElement, certifiedToscaElement));
+ private Either<ToscaElement, StorageOperationStatus> cloneToscaElementAndHandleRelations(GraphVertex toscaElement, GraphVertex modifier,
+ Integer majorVersion) {
+ return cloneToscaElementForCertify(toscaElement, modifier, majorVersion).right()
+ .map(status -> logDebugMessageAndReturnStorageOperationStatus(status, "Failed to clone tosca element during certification. ")).left()
+ .bind(certifiedToscaElement -> handleRelationsOfNewestCertifiedToscaElementAndReturn(toscaElement, certifiedToscaElement));
}
- private Either<ToscaElement, StorageOperationStatus> handleRelationsOfNewestCertifiedToscaElementAndReturn(
- GraphVertex toscaElement,
- GraphVertex certifiedToscaElement) {
- StorageOperationStatus status = handleRelationsOfNewestCertifiedToscaElement(toscaElement,
- certifiedToscaElement);
+ private Either<ToscaElement, StorageOperationStatus> handleRelationsOfNewestCertifiedToscaElementAndReturn(GraphVertex toscaElement,
+ GraphVertex certifiedToscaElement) {
+ StorageOperationStatus status = handleRelationsOfNewestCertifiedToscaElement(toscaElement, certifiedToscaElement);
if (status != StorageOperationStatus.OK) {
- return Either.right(
- logDebugMessageAndReturnStorageOperationStatus(status,
- "Failed to handle relations of newest certified tosca element {}. Status is {}. ",
- certifiedToscaElement.getUniqueId(), status));
+ return Either.right(logDebugMessageAndReturnStorageOperationStatus(status,
+ "Failed to handle relations of newest certified tosca element {}. Status is {}. ", certifiedToscaElement.getUniqueId(), status));
} else {
- return getToscaElementOperation(toscaElement.getLabel())
- .getToscaElement(certifiedToscaElement.getUniqueId());
+ return getToscaElementOperation(toscaElement.getLabel()).getToscaElement(certifiedToscaElement.getUniqueId());
}
}
- private static StorageOperationStatus logDebugMessageAndReturnStorageOperationStatus(
- final StorageOperationStatus status,
- final String msg,
- final Object... args) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, msg, args);
- return status;
- }
-
private StorageOperationStatus handleRelationsOfNewestCertifiedToscaElement(GraphVertex toscaElement, GraphVertex certifiedToscaElement) {
-
- JanusGraphOperationStatus createVersionEdgeStatus = janusGraphDao.createEdge(toscaElement, certifiedToscaElement, EdgeLabelEnum.VERSION, new HashMap<>());
+ JanusGraphOperationStatus createVersionEdgeStatus = janusGraphDao
+ .createEdge(toscaElement, certifiedToscaElement, EdgeLabelEnum.VERSION, new HashMap<>());
if (createVersionEdgeStatus != JanusGraphOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create version edge from last element {} to new certified element {}. status=", toscaElement.getUniqueId(), certifiedToscaElement.getUniqueId(),
- createVersionEdgeStatus);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create version edge from last element {} to new certified element {}. status=",
+ toscaElement.getUniqueId(), certifiedToscaElement.getUniqueId(), createVersionEdgeStatus);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createVersionEdgeStatus);
}
return StorageOperationStatus.OK;
@@ -408,7 +359,9 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
if (!(resourceToDelete.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) {
Either<GraphVertex, StorageOperationStatus> deleteElementRes = operation.markComponentToDelete(resourceToDelete);
if (deleteElementRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca element {}. Status is {}. ", resourceToDelete.getUniqueId(), deleteElementRes.right().value());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca element {}. Status is {}. ", resourceToDelete.getUniqueId(),
+ deleteElementRes.right().value());
result = Either.right(deleteElementRes.right().value());
break;
}
@@ -417,29 +370,31 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
return result;
}
- private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier, Integer majorVersion) {
+ private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier,
+ Integer majorVersion) {
StorageOperationStatus result = null;
if (majorVersion > 0) {
Either<Vertex, StorageOperationStatus> findRes = findLastCertifiedToscaElementVertex(toscaElement);
if (findRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch last certified tosca element {} . Status is {}. ", toscaElement.getMetadataProperty(GraphPropertyEnum.NAME), findRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch last certified tosca element {} . Status is {}. ",
+ toscaElement.getMetadataProperty(GraphPropertyEnum.NAME), findRes.right().value());
result = findRes.right().value();
}
if (result == null) {
Vertex lastCertifiedVertex = findRes.left().value();
Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
properties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false);
- JanusGraphOperationStatus status = janusGraphDao
- .updateVertexMetadataPropertiesWithJson(lastCertifiedVertex, properties);
+ JanusGraphOperationStatus status = janusGraphDao.updateVertexMetadataPropertiesWithJson(lastCertifiedVertex, properties);
if (status != JanusGraphOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set highest version of tosca element {} to [{}]. Status is {}", toscaElement.getUniqueId(), false, status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set highest version of tosca element {} to [{}]. Status is {}",
+ toscaElement.getUniqueId(), false, status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
// remove previous certified version from the catalog
GraphVertex lastCertifiedV = new GraphVertex();
lastCertifiedV.setVertex((JanusGraphVertex) lastCertifiedVertex);
- lastCertifiedV.setUniqueId((String) janusGraphDao
- .getProperty((JanusGraphVertex) lastCertifiedVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()));
+ lastCertifiedV.setUniqueId(
+ (String) janusGraphDao.getProperty((JanusGraphVertex) lastCertifiedVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()));
lastCertifiedV.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT,
(Boolean) janusGraphDao.getProperty((JanusGraphVertex) lastCertifiedVertex, GraphPropertyEnum.IS_ABSTRACT.getProperty()));
StorageOperationStatus res = updateEdgeToCatalogRoot(null, lastCertifiedV);
@@ -478,24 +433,23 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
private StorageOperationStatus updateOldToscaElementBeforeUndoCheckout(Vertex previousVersionToscaElement) {
-
StorageOperationStatus result = StorageOperationStatus.OK;
String previousVersion = (String) previousVersionToscaElement.property(GraphPropertyEnum.VERSION.getProperty()).value();
if (!previousVersion.endsWith(".0")) {
try {
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update vertex of previous version of tosca element", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()));
-
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update vertex of previous version of tosca element",
+ previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()));
Map<String, Object> propertiesToUpdate = new HashMap<>();
propertiesToUpdate.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true);
- Map<String, Object> jsonMetadataMap = JsonParserUtils.toMap((String) previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value());
+ Map<String, Object> jsonMetadataMap = JsonParserUtils
+ .toMap((String) previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value());
jsonMetadataMap.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true);
propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap));
-
janusGraphDao.setVertexProperties(previousVersionToscaElement, propertiesToUpdate);
-
Iterator<Edge> edgesIter = previousVersionToscaElement.edges(Direction.IN, EdgeLabelEnum.LAST_STATE.name());
if (!edgesIter.hasNext()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch last modifier vertex for tosca element {}. ", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()));
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch last modifier vertex for tosca element {}. ",
+ previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()));
result = StorageOperationStatus.NOT_FOUND;
} else {
Edge lastStateEdge = edgesIter.next();
@@ -503,16 +457,19 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
JanusGraphOperationStatus replaceRes = janusGraphDao
.replaceEdgeLabel(lastModifier, previousVersionToscaElement, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE);
if (replaceRes != JanusGraphOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE, replaceRes);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE,
+ EdgeLabelEnum.STATE, replaceRes);
result = StorageOperationStatus.INCONSISTENCY;
if (replaceRes != JanusGraphOperationStatus.INVALID_ID) {
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(replaceRes);
}
}
-
}
} catch (Exception e) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ", e.getMessage());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ",
+ e.getMessage());
}
}
return result;
@@ -527,18 +484,20 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
Either<GraphVertex, JanusGraphOperationStatus> updateVertexRes = janusGraphDao.updateVertex(toscaElementVertex);
if (updateVertexRes.isRight()) {
JanusGraphOperationStatus titatStatus = updateVertexRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update tosca element vertex {}. Status is {}", toscaElementVertex.getUniqueId(), titatStatus);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update tosca element vertex {}. Status is {}",
+ toscaElementVertex.getUniqueId(), titatStatus);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(titatStatus);
}
Either<Edge, JanusGraphOperationStatus> deleteEdgeRes = null;
if (result == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to replace edge with label {} to label {} from {} to {}. ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId);
-
- deleteEdgeRes = janusGraphDao
- .deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.TRACE, "Going to replace edge with label {} to label {} from {} to {}. ", EdgeLabelEnum.STATE,
+ EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId);
+ deleteEdgeRes = janusGraphDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE);
if (deleteEdgeRes.isRight()) {
JanusGraphOperationStatus janusGraphStatus = deleteEdgeRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge with label {} from {} to {}. Status is {} ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId, janusGraphStatus);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge with label {} from {} to {}. Status is {} ",
+ EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId, janusGraphStatus);
if (!janusGraphStatus.equals(JanusGraphOperationStatus.INVALID_ID)) {
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphStatus);
} else {
@@ -547,8 +506,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
}
if (result == null) {
- JanusGraphOperationStatus
- createEdgeRes = janusGraphDao
+ JanusGraphOperationStatus createEdgeRes = janusGraphDao
.createEdge(ownerVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_STATE, deleteEdgeRes.left().value());
if (createEdgeRes != JanusGraphOperationStatus.OK) {
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdgeRes);
@@ -562,7 +520,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
private Either<ToscaElement, StorageOperationStatus> cloneToscaElementForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) {
-
Either<ToscaElement, StorageOperationStatus> result = null;
Either<GraphVertex, StorageOperationStatus> cloneResult = null;
ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel());
@@ -572,13 +529,16 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
Vertex nextVersionVertex = nextVersionComponentIter.next().inVertex();
String fetchedVersion = (String) nextVersionVertex.property(GraphPropertyEnum.VERSION.getProperty()).value();
String fetchedName = (String) nextVersionVertex.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to checkout component {} with version {}. The component with name {} and version {} was fetched from graph as existing following version. ",
- toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString(), toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION).toString(), fetchedName, fetchedVersion);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to checkout component {} with version {}. The component with name {} and version {} was fetched from graph as existing following version. ",
+ toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString(),
+ toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION).toString(), fetchedName, fetchedVersion);
result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS);
}
if (result == null) {
toscaElementVertex.getOrSetDefaultInstantiationTypeForToscaElementJson();
- cloneResult = operation.cloneToscaElement(toscaElementVertex, cloneGraphVertexForCheckout(toscaElementVertex, modifierVertex), modifierVertex);
+ cloneResult = operation
+ .cloneToscaElement(toscaElementVertex, cloneGraphVertexForCheckout(toscaElementVertex, modifierVertex), modifierVertex);
if (cloneResult.isRight()) {
result = Either.right(cloneResult.right().value());
}
@@ -586,12 +546,13 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
GraphVertex clonedVertex = null;
if (result == null) {
clonedVertex = cloneResult.left().value();
- JanusGraphOperationStatus
- status = janusGraphDao
+ JanusGraphOperationStatus status = janusGraphDao
.createEdge(toscaElementVertex.getVertex(), cloneResult.left().value().getVertex(), EdgeLabelEnum.VERSION, new HashMap<>());
if (status != JanusGraphOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION,
- toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), cloneResult.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION,
+ toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME),
+ cloneResult.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
@@ -611,12 +572,13 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
result = handleFixTopologyTemplate(toscaElementVertex, result, operation, clonedVertex, toscaElement);
}
}
-
return result;
}
- private Either<ToscaElement, StorageOperationStatus> handleFixTopologyTemplate(GraphVertex toscaElementVertex, Either<ToscaElement, StorageOperationStatus> result, ToscaElementOperation operation, GraphVertex clonedVertex,
- ToscaElement toscaElement) {
+ private Either<ToscaElement, StorageOperationStatus> handleFixTopologyTemplate(GraphVertex toscaElementVertex,
+ Either<ToscaElement, StorageOperationStatus> result,
+ ToscaElementOperation operation, GraphVertex clonedVertex,
+ ToscaElement toscaElement) {
TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement;
Map<String, MapPropertiesDataDefinition> instInputs = topologyTemplate.getInstInputs();
Map<String, MapGroupsDataDefinition> instGroups = topologyTemplate.getInstGroups();
@@ -634,10 +596,10 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
Map<String, ComponentInstanceDataDefinition> instancesMap = topologyTemplate.getComponentInstances();
boolean isAddInstGroup = instGroups == null || instGroups.isEmpty();
boolean needUpdateComposition = false;
-
if (instancesMap != null && !instancesMap.isEmpty()) {
for (ComponentInstanceDataDefinition vfInst : instancesMap.values()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "vfInst name is {} . OriginType {}. ", vfInst.getName(), vfInst.getOriginType());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "vfInst name is {} . OriginType {}. ", vfInst.getName(), vfInst.getOriginType());
if (vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) {
collectInstanceInputAndGroups(instInputs, instGroups, instArtifactsMap, origCompMap, isAddInstGroup, vfInst, clonedVertex);
}
@@ -646,7 +608,9 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
instancesMap.put(vfInst.getUniqueId(), vfInst);
}
}
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add to graph instInputs {} instGroups {} needUpdateComposition {}", instInputs, instGroups, needUpdateComposition);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "before add to graph instInputs {} instGroups {} needUpdateComposition {}", instInputs,
+ instGroups, needUpdateComposition);
if (!instInputs.isEmpty()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add inst inputs {} ", instInputs == null ? 0 : instInputs.size());
GraphVertex toscaDataVertex = null;
@@ -655,14 +619,13 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
if (instInpVertexEither.isLeft()) {
toscaDataVertex = instInpVertexEither.left().value();
}
-
- StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, toscaDataVertex, instInputs);
+ StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, toscaDataVertex,
+ instInputs);
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update instance inputs . Status is {}. ", status);
result = Either.right(status);
return result;
}
-
}
if (!instGroups.isEmpty()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add inst groups {} ", instGroups == null ? 0 : instGroups.size());
@@ -672,14 +635,13 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
if (instGrVertexEither.isLeft()) {
toscaDataVertex = instGrVertexEither.left().value();
}
-
- StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, toscaDataVertex, instGroups);
+ StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, toscaDataVertex,
+ instGroups);
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update instance group . Status is {}. ", status);
result = Either.right(status);
return result;
}
-
}
if (needUpdateComposition) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before update Instances ");
@@ -694,9 +656,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
return result;
}
}
-
result = operation.getToscaElement(clonedVertex.getUniqueId());
-
} else {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "RI map empty on component {}", toscaElement.getUniqueId());
}
@@ -712,7 +672,8 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
if (vfInst.getToscaComponentName() == null || vfInst.getToscaComponentName().isEmpty()) {
String ciUid = vfInst.getUniqueId();
String origCompUid = vfInst.getComponentUid();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "fixToscaComponentName:: Ri id {} . origin component id is {}. type is{} ", ciUid, origCompUid, vfInst.getOriginType());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "fixToscaComponentName:: Ri id {} . origin component id is {}. type is{} ", ciUid,
+ origCompUid, vfInst.getOriginType());
ToscaElement origComp = null;
if (!origCompMap.containsKey(origCompUid)) {
Either<ToscaElement, StorageOperationStatus> origCompEither;
@@ -722,7 +683,8 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
origCompEither = nodeTypeOperation.getToscaElement(origCompUid);
}
if (origCompEither.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value());
return false;
}
origComp = origCompEither.left().value();
@@ -738,16 +700,19 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
return false;
}
- private void collectInstanceInputAndGroups(Map<String, MapPropertiesDataDefinition> instInputs, Map<String, MapGroupsDataDefinition> instGroups, Map<String, MapArtifactDataDefinition> instArtifactsMap, Map<String, ToscaElement> origCompMap,
- boolean isAddInstGroup, ComponentInstanceDataDefinition vfInst, GraphVertex clonedVertex) {
+ private void collectInstanceInputAndGroups(Map<String, MapPropertiesDataDefinition> instInputs, Map<String, MapGroupsDataDefinition> instGroups,
+ Map<String, MapArtifactDataDefinition> instArtifactsMap, Map<String, ToscaElement> origCompMap,
+ boolean isAddInstGroup, ComponentInstanceDataDefinition vfInst, GraphVertex clonedVertex) {
String ciUid = vfInst.getUniqueId();
String origCompUid = vfInst.getComponentUid();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "collectInstanceInputAndGroups:: Ri id {} . origin component id is {}. ", ciUid, origCompUid);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "collectInstanceInputAndGroups:: Ri id {} . origin component id is {}. ", ciUid, origCompUid);
TopologyTemplate origComp = null;
if (!origCompMap.containsKey(origCompUid)) {
Either<ToscaElement, StorageOperationStatus> origCompEither = topologyTemplateOperation.getToscaElement(origCompUid);
if (origCompEither.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value());
return;
}
origComp = (TopologyTemplate) origCompEither.left().value();
@@ -756,7 +721,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
origComp = (TopologyTemplate) origCompMap.get(origCompUid);
}
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Orig component {}. ", origComp.getUniqueId());
-
Map<String, PropertyDataDefinition> origInputs = origComp.getInputs();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Orig component inputs size {}. ", origInputs == null ? 0 : origInputs.size());
if (origInputs != null) {
@@ -764,7 +728,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(origInputs);
instInputs.put(ciUid, instProperties);
} else {
-
MapPropertiesDataDefinition instInputMap = instInputs.get(ciUid);
Map<String, PropertyDataDefinition> instProp = instInputMap.getMapToscaDataDefinition();
origInputs.forEach((propName, propMap) -> {
@@ -775,53 +738,48 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "ComponentInstanseInputs {}. ", instInputs.get(ciUid));
}
-
if (isAddInstGroup) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before create group instance. ");
List<GroupDataDefinition> filteredGroups = null;
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups before filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups before filter. Size is {} ",
+ filteredGroups == null ? 0 : filteredGroups.size());
if (origComp.getGroups() != null && !origComp.getGroups().isEmpty()) {
filteredGroups = origComp.getGroups().values().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups . Size is {} ", filteredGroups == null ? 0 : filteredGroups.size());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups . Size is {} ", filteredGroups == null ? 0 : filteredGroups.size());
}
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups after filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups after filter. Size is {} ",
+ filteredGroups == null ? 0 : filteredGroups.size());
if (CollectionUtils.isNotEmpty(filteredGroups)) {
MapArtifactDataDefinition instArifacts = null;
if (!instArtifactsMap.containsKey(ciUid)) {
-
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "istance artifacts not found ");
-
Map<String, ArtifactDataDefinition> deploymentArtifacts = origComp.getDeploymentArtifacts();
-
instArifacts = new MapArtifactDataDefinition(deploymentArtifacts);
- addToscaDataDeepElementsBlockToToscaElement(clonedVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArifacts, ciUid);
-
+ addToscaDataDeepElementsBlockToToscaElement(clonedVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS,
+ VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArifacts, ciUid);
instArtifactsMap.put(ciUid, instArifacts);
-
} else {
instArifacts = instArtifactsMap.get(ciUid);
}
-
if (instArifacts != null) {
Map<String, ArtifactDataDefinition> instDeplArtifMap = instArifacts.getMapToscaDataDefinition();
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check group dep artifacts. Size is {} ", instDeplArtifMap == null ? 0 : instDeplArtifMap.values().size());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check group dep artifacts. Size is {} ",
+ instDeplArtifMap == null ? 0 : instDeplArtifMap.values().size());
Map<String, GroupInstanceDataDefinition> groupInstanceToCreate = new HashMap<>();
for (GroupDataDefinition group : filteredGroups) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "create new groupInstance {} ", group.getName());
GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition(group, vfInst, instDeplArtifMap);
List<String> artifactsUid = new ArrayList<>();
List<String> artifactsId = new ArrayList<>();
- if (instDeplArtifMap!=null) {
- for (ArtifactDataDefinition artifact : instDeplArtifMap.values()) {
- Optional<String> op = group.getArtifacts().stream().filter(p -> p.equals(artifact.getGeneratedFromId())).findAny();
- if (op.isPresent()) {
- artifactsUid.add(artifact.getArtifactUUID());
- artifactsId.add(artifact.getUniqueId());
-
- }
- }
+ if (instDeplArtifMap != null) {
+ for (ArtifactDataDefinition artifact : instDeplArtifMap.values()) {
+ Optional<String> op = group.getArtifacts().stream().filter(p -> p.equals(artifact.getGeneratedFromId())).findAny();
+ if (op.isPresent()) {
+ artifactsUid.add(artifact.getArtifactUUID());
+ artifactsId.add(artifact.getUniqueId());
+ }
+ }
}
groupInstance.setGroupInstanceArtifacts(artifactsId);
groupInstance.setGroupInstanceArtifactsUuid(artifactsUid);
@@ -829,7 +787,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
if (MapUtils.isNotEmpty(groupInstanceToCreate)) {
instGroups.put(vfInst.getUniqueId(), new MapGroupsDataDefinition(groupInstanceToCreate));
-
}
}
}
@@ -844,7 +801,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
nextVersionToscaElementVertex.setUniqueId(uniqueId);
nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel());
nextVersionToscaElementVertex.setType(toscaElementVertex.getType());
-
nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId);
nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name());
String nextVersion = getNextVersion((String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION));
@@ -854,9 +810,9 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, nextVersion);
nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) {
- nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ nextVersionToscaElementVertex
+ .addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
}
if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) {
nextVersionToscaElementVertex.setMetadataJson(new HashMap<>(toscaElementVertex.getMetadataJson()));
@@ -868,67 +824,53 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId());
nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId());
if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) {
- nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CONFORMANCE_LEVEL, ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
+ nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CONFORMANCE_LEVEL,
+ ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
}
-
if (!MapUtils.isEmpty(toscaElementVertex.getJson())) {
nextVersionToscaElementVertex.setJson(new HashMap<String, ToscaDataDefinition>(toscaElementVertex.getJson()));
}
return nextVersionToscaElementVertex;
}
- private Either<GraphVertex, StorageOperationStatus> cloneToscaElementForCertify(GraphVertex toscaElementVertex,
- GraphVertex modifierVertex, Integer majorVersion) {
+ private Either<GraphVertex, StorageOperationStatus> cloneToscaElementForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex,
+ Integer majorVersion) {
return getToscaElementOperation(toscaElementVertex.getLabel())
- .cloneToscaElement(
- toscaElementVertex,
- cloneGraphVertexForCertify(toscaElementVertex, modifierVertex, majorVersion),
- modifierVertex)
- .right().map(status ->
- logDebugMessageAndReturnStorageOperationStatus(status,
- "Failed to clone tosca element {} for certification. Status is {}. ",
- toscaElementVertex.getUniqueId(), status))
- .left().bind(clonedToscaElement ->
- updateEdgesDeleteNotCertifiedVersionsAndHandlePreviousVersions(
- clonedToscaElement, toscaElementVertex, majorVersion
- ));
+ .cloneToscaElement(toscaElementVertex, cloneGraphVertexForCertify(toscaElementVertex, modifierVertex, majorVersion), modifierVertex)
+ .right().map(
+ status -> logDebugMessageAndReturnStorageOperationStatus(status, "Failed to clone tosca element {} for certification. Status is {}. ",
+ toscaElementVertex.getUniqueId(), status)).left().bind(
+ clonedToscaElement -> updateEdgesDeleteNotCertifiedVersionsAndHandlePreviousVersions(clonedToscaElement, toscaElementVertex,
+ majorVersion));
}
- private Either<GraphVertex, StorageOperationStatus> updateEdgesDeleteNotCertifiedVersionsAndHandlePreviousVersions(
- GraphVertex clonedToscaElement,
- GraphVertex toscaElementVertex,
- Integer majorVersion
- ) {
+ private Either<GraphVertex, StorageOperationStatus> updateEdgesDeleteNotCertifiedVersionsAndHandlePreviousVersions(GraphVertex clonedToscaElement,
+ GraphVertex toscaElementVertex,
+ Integer majorVersion) {
StorageOperationStatus updateEdgeToCatalog = updateEdgeToCatalogRoot(clonedToscaElement, toscaElementVertex);
if (updateEdgeToCatalog != StorageOperationStatus.OK) {
return Either.right(updateEdgeToCatalog);
} else {
- Either<List<GraphVertex>, StorageOperationStatus> deleteResultEither =
- deleteAllPreviousNotCertifiedVersions(toscaElementVertex);
-
- if (deleteResultEither == null) {
- return Either.right(
- logDebugMessageAndReturnStorageOperationStatus(StorageOperationStatus.GENERAL_ERROR,
- "Failed to delete all previous not certified versions of tosca element {}. Null value returned.",
- toscaElementVertex.getUniqueId()));
+ Either<List<GraphVertex>, StorageOperationStatus> deleteResultEither = deleteAllPreviousNotCertifiedVersions(toscaElementVertex);
+ if (deleteResultEither == null) {
+ return Either.right(logDebugMessageAndReturnStorageOperationStatus(StorageOperationStatus.GENERAL_ERROR,
+ "Failed to delete all previous not certified versions of tosca element {}. Null value returned.",
+ toscaElementVertex.getUniqueId()));
} else {
- return deleteResultEither
- .right().map(status ->
- logDebugMessageAndReturnStorageOperationStatus(status,
- "Failed to delete all previous not certified versions of tosca element {}. Status is {}. ",
- toscaElementVertex.getUniqueId(), status))
- .left().bind(deleteResult ->
- handlePreviousVersionRelation(clonedToscaElement, deleteResult, majorVersion));
+ return deleteResultEither.right().map(status -> logDebugMessageAndReturnStorageOperationStatus(status,
+ "Failed to delete all previous not certified versions of tosca element {}. Status is {}. ", toscaElementVertex.getUniqueId(),
+ status)).left().bind(deleteResult -> handlePreviousVersionRelation(clonedToscaElement, deleteResult, majorVersion));
}
}
}
- private Either<GraphVertex, StorageOperationStatus> handlePreviousVersionRelation(GraphVertex clonedToscaElement, List<GraphVertex> deletedVersions, Integer majorVersion) {
+ private Either<GraphVertex, StorageOperationStatus> handlePreviousVersionRelation(GraphVertex clonedToscaElement,
+ List<GraphVertex> deletedVersions, Integer majorVersion) {
Either<GraphVertex, StorageOperationStatus> result = null;
Vertex previousCertifiedToscaElement = null;
if (majorVersion > 0) {
- List<GraphVertex> firstMinorVersionVertex = deletedVersions.stream().filter(gv -> getMinorVersion((String) gv.getMetadataProperty(GraphPropertyEnum.VERSION)) == 1).collect(Collectors.toList());
-
+ List<GraphVertex> firstMinorVersionVertex = deletedVersions.stream()
+ .filter(gv -> getMinorVersion((String) gv.getMetadataProperty(GraphPropertyEnum.VERSION)) == 1).collect(Collectors.toList());
if (CollectionUtils.isEmpty(firstMinorVersionVertex)) {
result = Either.right(StorageOperationStatus.NOT_FOUND);
} else {
@@ -938,16 +880,16 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
}
if (result == null) {
- JanusGraphOperationStatus
- status = janusGraphDao
+ JanusGraphOperationStatus status = janusGraphDao
.createEdge(previousCertifiedToscaElement, clonedToscaElement.getVertex(), EdgeLabelEnum.VERSION, new HashMap<>());
if (status != JanusGraphOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION,
- previousCertifiedToscaElement.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), clonedToscaElement.getUniqueId(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ",
+ EdgeLabelEnum.VERSION, previousCertifiedToscaElement.property(GraphPropertyEnum.UNIQUE_ID.getProperty()),
+ clonedToscaElement.getUniqueId(), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
-
}
if (result == null) {
result = Either.left(clonedToscaElement);
@@ -956,7 +898,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
private Vertex getPreviousCertifiedToscaElement(GraphVertex graphVertex) {
-
Iterator<Edge> edges = graphVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name());
if (edges.hasNext()) {
return edges.next().outVertex();
@@ -966,7 +907,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
private Either<List<GraphVertex>, StorageOperationStatus> deleteAllPreviousNotCertifiedVersions(GraphVertex toscaElementVertex) {
Either<List<GraphVertex>, StorageOperationStatus> result = null;
-
ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel());
List<GraphVertex> previosVersions = null;
Object uuid = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.UUID);
@@ -991,13 +931,14 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
result = Either.left(previosVersions);
}
} catch (Exception e) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occurred during deleting all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occurred during deleting all tosca elements by UUID {} and name {}. {} ", uuid,
+ componentName, e.getMessage());
}
return result;
}
private GraphVertex cloneGraphVertexForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) {
-
GraphVertex nextVersionToscaElementVertex = new GraphVertex();
String uniqueId = IdBuilderUtils.generateUniqueId();
Map<GraphPropertyEnum, Object> metadataProperties = new EnumMap<>(toscaElementVertex.getMetadataProperties());
@@ -1005,7 +946,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
nextVersionToscaElementVertex.setUniqueId(uniqueId);
nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel());
nextVersionToscaElementVertex.setType(toscaElementVertex.getType());
-
nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId);
nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name());
nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, (majorVersion + 1) + VERSION_DELIMITER + "0");
@@ -1015,9 +955,9 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, null);
nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId());
nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId());
-
if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) {
- nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ nextVersionToscaElementVertex
+ .addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
}
if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) {
nextVersionToscaElementVertex.setMetadataJson(new HashMap<>(toscaElementVertex.getMetadataJson()));
@@ -1029,8 +969,9 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
return nextVersionToscaElementVertex;
}
-
- private Either<GraphVertex, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex, LifecycleStateEnum nextState) {
+ private Either<GraphVertex, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, GraphVertex toscaElementVertex,
+ GraphVertex ownerVertex, GraphVertex modifierVertex,
+ LifecycleStateEnum nextState) {
Either<GraphVertex, StorageOperationStatus> updateRelationsRes;
Either<GraphVertex, StorageOperationStatus> result = changeStateToCheckedIn(currState, toscaElementVertex, ownerVertex, modifierVertex);
if (result.isLeft()) {
@@ -1048,13 +989,12 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
private Either<GraphVertex, StorageOperationStatus> updateToscaElementVertexMetadataPropertiesAndJson(GraphVertex toscaElementVertex) {
-
Either<GraphVertex, StorageOperationStatus> result;
-
Either<GraphVertex, JanusGraphOperationStatus> updateVertexRes = janusGraphDao.updateVertex(toscaElementVertex);
if (updateVertexRes.isRight()) {
JanusGraphOperationStatus titatStatus = updateVertexRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update state of tosca element vertex {} metadata. Status is {}", toscaElementVertex.getUniqueId(), titatStatus);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update state of tosca element vertex {} metadata. Status is {}",
+ toscaElementVertex.getUniqueId(), titatStatus);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(titatStatus));
} else {
result = Either.left(updateVertexRes.left().value());
@@ -1062,25 +1002,22 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
return result;
}
- private Either<GraphVertex, StorageOperationStatus> changeStateToCheckedIn(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) {
+ private Either<GraphVertex, StorageOperationStatus> changeStateToCheckedIn(LifecycleStateEnum currState, GraphVertex toscaElementVertex,
+ GraphVertex ownerVertex, GraphVertex modifierVertex) {
Either<GraphVertex, StorageOperationStatus> result = null;
LifecycleStateEnum nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN;
String faileToUpdateStateMsg = "Failed to update state of tosca element {}. Status is {}";
-
// Remove CHECKOUT relation
- Either<Edge, JanusGraphOperationStatus> deleteEdgeResult = janusGraphDao
- .deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE);
+ Either<Edge, JanusGraphOperationStatus> deleteEdgeResult = janusGraphDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE);
if (deleteEdgeResult.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId());
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteEdgeResult.right().value()));
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteEdgeResult.right().value()));
}
-
if (result == null) {
// Create CHECKIN relation
Map<EdgePropertyEnum, Object> edgeProperties = new EnumMap<>(EdgePropertyEnum.class);
edgeProperties.put(EdgePropertyEnum.STATE, nextState);
- JanusGraphOperationStatus
- createEdgeRes = janusGraphDao
+ JanusGraphOperationStatus createEdgeRes = janusGraphDao
.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.STATE, edgeProperties);
if (createEdgeRes != JanusGraphOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId());
@@ -1093,21 +1030,24 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
return result;
}
- private Either<GraphVertex, StorageOperationStatus> updateLastModifierEdge(GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) {
+ private Either<GraphVertex, StorageOperationStatus> updateLastModifierEdge(GraphVertex toscaElementVertex, GraphVertex ownerVertex,
+ GraphVertex modifierVertex) {
Either<GraphVertex, StorageOperationStatus> result = null;
- if (!modifierVertex.getMetadataProperties().get(GraphPropertyEnum.USERID).equals(ownerVertex.getMetadataProperties().get(GraphPropertyEnum.USERID))) {
+ if (!modifierVertex.getMetadataProperties().get(GraphPropertyEnum.USERID)
+ .equals(ownerVertex.getMetadataProperties().get(GraphPropertyEnum.USERID))) {
Either<Edge, JanusGraphOperationStatus> deleteEdgeRes = janusGraphDao
.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.LAST_MODIFIER);
if (deleteEdgeRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete last modifier {} to tosca element {}. Edge type is {}", ownerVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete last modifier {} to tosca element {}. Edge type is {}",
+ ownerVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteEdgeRes.right().value()));
}
if (result == null) {
JanusGraphOperationStatus createEdgeRes = janusGraphDao
.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
-
if (createEdgeRes != JanusGraphOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate user {} to component {}. Edge type is {}", modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate user {} to component {}. Edge type is {}",
+ modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdgeRes));
} else {
result = Either.left(modifierVertex);
@@ -1119,7 +1059,9 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
return result;
}
- private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckin(String toscaElementId, String modifierId, String ownerId) {
+ private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckin(String toscaElementId,
+ String modifierId,
+ String ownerId) {
Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>();
verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseMetadata));
verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
@@ -1127,7 +1069,8 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
return verticesToGetParameters;
}
- private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForRequestCertification(String toscaElementId, String modifierId, String ownerId) {
+ private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForRequestCertification(
+ String toscaElementId, String modifierId, String ownerId) {
Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>();
verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll));
verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse));
@@ -1135,9 +1078,11 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
return verticesToGetParameters;
}
- private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckout(String toscaElementId, String modifierId, String ownerId) {
- //Implementation is currently identical
- return prepareParametersToGetVerticesForRequestCertification(toscaElementId,modifierId, ownerId);
+ private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckout(String toscaElementId,
+ String modifierId,
+ String ownerId) {
+ //Implementation is currently identical
+ return prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId);
}
private String getNextCertifiedVersion(String version) {
@@ -1163,10 +1108,12 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
private boolean isFirstCheckoutAfterCertification(String version) {
- return (Integer.parseInt(version.split(VERSION_DELIMITER_REGEXP)[0]) != 0 && Integer.parseInt(version.split(VERSION_DELIMITER_REGEXP)[1]) == 1);
+ return (Integer.parseInt(version.split(VERSION_DELIMITER_REGEXP)[0]) != 0
+ && Integer.parseInt(version.split(VERSION_DELIMITER_REGEXP)[1]) == 1);
}
- public Either<ToscaElement, StorageOperationStatus> forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId, String currVersion) {
+ public Either<ToscaElement, StorageOperationStatus> forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId,
+ String currVersion) {
Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
Either<ToscaElement, StorageOperationStatus> result = null;
GraphVertex toscaElement = null;
@@ -1183,21 +1130,21 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
toscaElement = getVerticesRes.left().value().get(toscaElementId);
modifier = getVerticesRes.left().value().get(modifierId);
owner = getVerticesRes.left().value().get(ownerId);
-
StorageOperationStatus status = handleRelationsUponForceCertification(toscaElement, modifier, owner);
if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(),
+ status);
}
}
if (result == null) {
LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFIED;
-
toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
toscaElement.addMetadataProperty(GraphPropertyEnum.VERSION, getNextCertifiedVersion(currVersion));
-
resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement);
if (resultUpdate.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}",
+ toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
result = Either.right(resultUpdate.right().value());
}
}
@@ -1206,15 +1153,15 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
result = operation.getToscaElement(toscaElement.getUniqueId());
}
return result;
-
} catch (Exception e) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId,
+ e.getMessage());
}
return result;
}
private StorageOperationStatus handleRelationsUponForceCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
-
StorageOperationStatus result = null;
JanusGraphOperationStatus status = janusGraphDao
.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
@@ -1224,8 +1171,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
if (result == null) {
Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED);
- status = janusGraphDao
- .createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties);
+ status = janusGraphDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties);
if (status != JanusGraphOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
@@ -1241,16 +1187,13 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
if (preV == null) {
return updateEdgeToCatalogRoot(null, curV);
}
- String uniqueIdPreVer = (String) janusGraphDao
- .getProperty((JanusGraphVertex) preV, GraphPropertyEnum.UNIQUE_ID.getProperty());
- LifecycleStateEnum state = LifecycleStateEnum.findState((String) janusGraphDao
- .getProperty(preV, GraphPropertyEnum.STATE.getProperty()));
+ String uniqueIdPreVer = (String) janusGraphDao.getProperty((JanusGraphVertex) preV, GraphPropertyEnum.UNIQUE_ID.getProperty());
+ LifecycleStateEnum state = LifecycleStateEnum.findState((String) janusGraphDao.getProperty(preV, GraphPropertyEnum.STATE.getProperty()));
if (state == LifecycleStateEnum.CERTIFIED) {
return updateEdgeToCatalogRoot(null, curV);
}
return janusGraphDao.getVertexById(uniqueIdPreVer)
- .either(l -> updateEdgeToCatalogRoot(l, curV),
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .either(l -> updateEdgeToCatalogRoot(l, curV), DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
private StorageOperationStatus updateEdgeToCatalogRoot(GraphVertex newVersionV, GraphVertex prevVersionV) {
@@ -1262,14 +1205,12 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
GraphVertex catalogV = catalog.left().value();
if (newVersionV != null) {
Boolean isAbstract = (Boolean) newVersionV.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT);
-
- if ( isAbstract == null || !isAbstract ) {
+ if (isAbstract == null || !isAbstract) {
// create new vertex
- JanusGraphOperationStatus
- result = janusGraphDao
- .createEdge(catalogV, newVersionV, EdgeLabelEnum.CATALOG_ELEMENT, null);
+ JanusGraphOperationStatus result = janusGraphDao.createEdge(catalogV, newVersionV, EdgeLabelEnum.CATALOG_ELEMENT, null);
if (result != JanusGraphOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge from {} to catalog vertex. error {}", newVersionV.getUniqueId(), result);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge from {} to catalog vertex. error {}",
+ newVersionV.getUniqueId(), result);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
}
}
@@ -1281,7 +1222,8 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
Either<Edge, JanusGraphOperationStatus> deleteResult = janusGraphDao
.deleteEdge(catalogV, prevVersionV, EdgeLabelEnum.CATALOG_ELEMENT);
if (deleteResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge from {} to catalog vertex. error {}", prevVersionV.getUniqueId(), deleteResult.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge from {} to catalog vertex. error {}",
+ prevVersionV.getUniqueId(), deleteResult.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteResult.right().value());
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java
index bb3b3b8cf2..884f040d07 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import static org.openecomp.sdc.be.utils.TypeUtils.setField;
@@ -45,7 +44,6 @@ import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.janusgraph.core.JanusGraphVertex;
-import org.onap.sdc.tosca.datatypes.model.EntrySchema;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
@@ -58,7 +56,6 @@ import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.category.MetadataKeyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -89,37 +86,56 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;
public abstract class ToscaElementOperation extends BaseOperation {
- private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}";
+ private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}";
private static final String CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS = "Cannot find user {} in the graph. status is {}";
-
private static final String FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ";
-
private static final String FAILED_TO_GET_CREATOR_VERTEX_OF_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to get creator vertex with label {} of tosca element vertex {} on graph. Status is {}. ";
-
- private static Logger log = Logger.getLogger(ToscaElementOperation.class.getName());
-
private static final Gson gson = new Gson();
-
+ private static Logger log = Logger.getLogger(ToscaElementOperation.class.getName());
@Autowired
protected CategoryOperation categoryOperation;
+ public static DataTypeDefinition createDataType(final String dataTypeName) {
+ final DataTypeDefinition dataType = new DataTypeDefinition();
+ dataType.setName(dataTypeName);
+ return dataType;
+ }
+
+ public static DataTypeDefinition createDataTypeDefinitionWithName(final Entry<String, Object> attributeNameValue) {
+ final Map<String, Object> attributeMap = (Map<String, Object>) attributeNameValue.getValue();
+ final DataTypeDefinition dataType = createDataType(attributeNameValue.getKey());
+ setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, dataType::setDescription);
+ setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM_NAME, dataType::setDerivedFromName);
+ // TODO - find the way to set the properties
+
+// CommonImportManager.setProperties(attributeMap, dataType::setProperties);
+ final Object derivedFrom = attributeMap.get(JsonPresentationFields.DERIVED_FROM.getPresentation());
+ if (derivedFrom instanceof Map) {
+ final Map<String, Object> derivedFromMap = (Map<String, Object>) derivedFrom;
+ final DataTypeDefinition parentDataTypeDataDefinition = new DataTypeDefinition();
+ parentDataTypeDataDefinition.setName((String) derivedFromMap.get(JsonPresentationFields.NAME.getPresentation()));
+ parentDataTypeDataDefinition.setUniqueId((String) derivedFromMap.get(JsonPresentationFields.UNIQUE_ID.getPresentation()));
+ parentDataTypeDataDefinition.setCreationTime((Long) derivedFromMap.get(JsonPresentationFields.CREATION_TIME.getPresentation()));
+ parentDataTypeDataDefinition.setModificationTime((Long) derivedFromMap.get(JsonPresentationFields.MODIFICATION_TIME.getPresentation()));
+ dataType.setDerivedFrom(parentDataTypeDataDefinition);
+ }
+ return dataType;
+ }
+
protected Gson getGson() {
return gson;
}
- protected Either<GraphVertex, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType, JsonParseFlagEnum parseFlag) {
-
+ protected Either<GraphVertex, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType,
+ JsonParseFlagEnum parseFlag) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId);
-
VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType);
- Either<List<GraphVertex>, JanusGraphOperationStatus> getResponse = janusGraphDao
- .getByCriteria(vertexType, propertiesToMatch, parseFlag);
+ Either<List<GraphVertex>, JanusGraphOperationStatus> getResponse = janusGraphDao.getByCriteria(vertexType, propertiesToMatch, parseFlag);
if (getResponse.isRight()) {
log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", vertexType, uniqueId, getResponse.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value()));
-
}
List<GraphVertex> componentList = getResponse.left().value();
if (componentList.isEmpty()) {
@@ -141,9 +157,7 @@ public abstract class ToscaElementOperation extends BaseOperation {
} else {
componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE);
componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
-
Either<GraphVertex, JanusGraphOperationStatus> updateNode = janusGraphDao.updateVertex(componentToDelete);
-
StorageOperationStatus updateComponent;
if (updateNode.isRight()) {
log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value());
@@ -162,16 +176,16 @@ public abstract class ToscaElementOperation extends BaseOperation {
* @param user
* @return
*/
- public Either<GraphVertex, StorageOperationStatus> cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement, GraphVertex user) {
-
+ public Either<GraphVertex, StorageOperationStatus> cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement,
+ GraphVertex user) {
Either<GraphVertex, StorageOperationStatus> result = null;
GraphVertex createdToscaElementVertex = null;
JanusGraphOperationStatus status;
-
Either<GraphVertex, JanusGraphOperationStatus> createNextVersionRes = janusGraphDao.createVertex(nextToscaElement);
if (createNextVersionRes.isRight()) {
status = createNextVersionRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ", previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME),
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ",
+ previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME),
previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
@@ -179,39 +193,39 @@ public abstract class ToscaElementOperation extends BaseOperation {
createdToscaElementVertex = createNextVersionRes.left().value();
final Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE));
- status = janusGraphDao
- .createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties);
+ status = janusGraphDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties);
if (status != JanusGraphOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.STATE, user.getUniqueId(),
- previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.STATE,
+ user.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
if (result == null) {
- status = janusGraphDao
- .createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
+ status = janusGraphDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
if (status != JanusGraphOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.LAST_MODIFIER, user.getUniqueId(),
- nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.LAST_MODIFIER,
+ user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
if (result == null) {
- Either<GraphVertex, JanusGraphOperationStatus> creatorVertexRes = janusGraphDao.getParentVertex(previousToscaElement,
- EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, JanusGraphOperationStatus> creatorVertexRes = janusGraphDao
+ .getParentVertex(previousToscaElement, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse);
if (creatorVertexRes.isRight()) {
status = creatorVertexRes.right().value();
- CommonUtility.addRecordToLog(log,
- LogLevelEnum.DEBUG, FAILED_TO_GET_CREATOR_VERTEX_OF_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS,
- EdgeLabelEnum.CREATOR,
- nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CREATOR_VERTEX_OF_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS,
+ EdgeLabelEnum.CREATOR, nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
- status = janusGraphDao.createEdge(creatorVertexRes.left().value().getVertex(), createdToscaElementVertex.getVertex(),
- EdgeLabelEnum.CREATOR, new HashMap<>());
+ status = janusGraphDao
+ .createEdge(creatorVertexRes.left().value().getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR,
+ new HashMap<>());
if (status != JanusGraphOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.CREATOR, user.getUniqueId(),
- nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.CREATOR,
+ user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
@@ -223,18 +237,21 @@ public abstract class ToscaElementOperation extends BaseOperation {
status = janusGraphDao
.createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge);
if (status != JanusGraphOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ", currEdge.label(), createdToscaElementVertex.getUniqueId(),
- currVertex.property(GraphPropertyEnum.LABEL.getProperty()), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ",
+ currEdge.label(), createdToscaElementVertex.getUniqueId(), currVertex.property(GraphPropertyEnum.LABEL.getProperty()),
+ status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
break;
}
}
}
-
if (result == null) {
result = Either.left(createdToscaElementVertex);
} else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME));
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(),
+ previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME));
}
return result;
}
@@ -254,7 +271,6 @@ public abstract class ToscaElementOperation extends BaseOperation {
}
public String buildFullName(GraphVertex userV) {
-
String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME);
if (fullName == null) {
fullName = "";
@@ -279,7 +295,6 @@ public abstract class ToscaElementOperation extends BaseOperation {
String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
toscaElement.setCreatorUserId(creatorUserId);
toscaElement.setCreatorFullName(buildFullName(userV));
-
return JanusGraphOperationStatus.OK;
}
@@ -290,7 +305,6 @@ public abstract class ToscaElementOperation extends BaseOperation {
if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) {
toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName()));
}
-
LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState();
if (lifecycleStateEnum == null) {
toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
@@ -300,7 +314,6 @@ public abstract class ToscaElementOperation extends BaseOperation {
toscaElement.setCreationDate(currentDate);
}
toscaElement.setLastUpdateDate(currentDate);
-
return toscaElement;
}
@@ -309,13 +322,15 @@ public abstract class ToscaElementOperation extends BaseOperation {
toscaElement.setHighestVersion(true);
}
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION,
+ toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
+ nodeTypeVertex
+ .addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID));
@@ -324,8 +339,8 @@ public abstract class ToscaElementOperation extends BaseOperation {
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_ARCHIVED));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, toscaElement.getMetadataValue(JsonPresentationFields.ARCHIVE_TIME));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED));
- toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null).forEach(e -> nodeTypeVertex.setJsonMetadataField(e.getKey(), e.getValue()));
-
+ toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null)
+ .forEach(e -> nodeTypeVertex.setJsonMetadataField(e.getKey(), e.getValue()));
nodeTypeVertex.setUniqueId(toscaElement.getUniqueId());
nodeTypeVertex.setType(toscaElement.getComponentType());
final String toscaVersion = toscaElement.getToscaVersion();
@@ -341,14 +356,11 @@ public abstract class ToscaElementOperation extends BaseOperation {
protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
// handle user
String userId = toscaElement.getCreatorUserId();
-
Either<GraphVertex, JanusGraphOperationStatus> findUser = findUserVertex(userId);
-
if (findUser.isRight()) {
JanusGraphOperationStatus status = findUser.right().value();
log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
-
}
GraphVertex creatorVertex = findUser.left().value();
GraphVertex updaterVertex = creatorVertex;
@@ -365,29 +377,26 @@ public abstract class ToscaElementOperation extends BaseOperation {
}
Map<EdgePropertyEnum, Object> props = new EnumMap<>(EdgePropertyEnum.class);
props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
-
- JanusGraphOperationStatus
- result = janusGraphDao
- .createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props);
+ JanusGraphOperationStatus result = janusGraphDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props);
log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE);
if (JanusGraphOperationStatus.OK != result) {
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
}
- result = janusGraphDao
- .createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null);
- log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
+ result = janusGraphDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null);
+ log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(),
+ EdgeLabelEnum.LAST_MODIFIER);
if (!result.equals(JanusGraphOperationStatus.OK)) {
- log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
+ log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(),
+ EdgeLabelEnum.LAST_MODIFIER);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
}
-
toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId());
toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName());
-
result = janusGraphDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null);
log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR);
if (!result.equals(JanusGraphOperationStatus.OK)) {
- log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR);
+ log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(),
+ EdgeLabelEnum.CREATOR);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
}
return StorageOperationStatus.OK;
@@ -396,19 +405,16 @@ public abstract class ToscaElementOperation extends BaseOperation {
protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName();
String categoryName = nodeType.getCategories().get(0).getName();
- Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName, categoryName);
-
+ Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName,
+ categoryName);
if (getCategoryVertex.isRight()) {
return getCategoryVertex.right().value();
}
-
GraphVertex subCategoryV = getCategoryVertex.left().value();
-
- JanusGraphOperationStatus
- createEdge = janusGraphDao
- .createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
+ JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
if (createEdge != JanusGraphOperationStatus.OK) {
- log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName, subCategoryV.getUniqueId());
+ log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName,
+ subCategoryV.getUniqueId());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
}
return StorageOperationStatus.OK;
@@ -421,14 +427,13 @@ public abstract class ToscaElementOperation extends BaseOperation {
return Either.right(category.right().value());
}
GraphVertex categoryV = category.left().value();
-
if (subcategoryName != null) {
Either<GraphVertex, StorageOperationStatus> subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName);
if (subCategory.isRight()) {
- log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId, subCategory.right().value());
+ log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId,
+ subCategory.right().value());
return Either.right(subCategory.right().value());
}
-
GraphVertex subCategoryV = subCategory.left().value();
return Either.left(subCategoryV);
}
@@ -440,7 +445,8 @@ public abstract class ToscaElementOperation extends BaseOperation {
Either<GraphVertex, StorageOperationStatus> status;
if (artifacts != null) {
artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
+ String uniqueId = UniqueIdBuilder
+ .buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
a.setUniqueId(uniqueId);
});
status = associateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts);
@@ -451,7 +457,8 @@ public abstract class ToscaElementOperation extends BaseOperation {
Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts();
if (toscaArtifacts != null) {
toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
+ String uniqueId = UniqueIdBuilder
+ .buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
a.setUniqueId(uniqueId);
});
status = associateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts);
@@ -462,10 +469,12 @@ public abstract class ToscaElementOperation extends BaseOperation {
Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts();
if (deploymentArtifacts != null) {
deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
+ String uniqueId = UniqueIdBuilder
+ .buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
a.setUniqueId(uniqueId);
});
- status = associateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, deploymentArtifacts);
+ status = associateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS,
+ deploymentArtifacts);
if (status.isRight()) {
return status.right().value();
}
@@ -474,57 +483,47 @@ public abstract class ToscaElementOperation extends BaseOperation {
}
protected JanusGraphOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) {
- JanusGraphOperationStatus
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS);
+ JanusGraphOperationStatus status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
- status = janusGraphDao
- .disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH);
+ status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
@@ -536,8 +535,8 @@ public abstract class ToscaElementOperation extends BaseOperation {
return assosiateCommonForToscaElement(nodeTypeVertex, toscaElement, null);
}
- protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement, List<GraphVertex> derivedResources) {
-
+ protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement,
+ List<GraphVertex> derivedResources) {
StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement);
if (associateUsers != StorageOperationStatus.OK) {
return associateUsers;
@@ -577,29 +576,25 @@ public abstract class ToscaElementOperation extends BaseOperation {
log.debug("Failed to fetch catalog vertex. error {}", catalog.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(catalog.right().value());
}
- JanusGraphOperationStatus
- createEdge = janusGraphDao
- .createEdge(catalog.left().value(), nodeTypeVertex, EdgeLabelEnum.CATALOG_ELEMENT, null);
-
+ JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(catalog.left().value(), nodeTypeVertex, EdgeLabelEnum.CATALOG_ELEMENT, null);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
}
- protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List<GraphVertex> derivedResources) {
+ protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType,
+ List<GraphVertex> derivedResources) {
// Note : currently only one derived supported!!!!
- Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.PROPERTIES);
+ Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources,
+ EdgeLabelEnum.PROPERTIES);
if (dataFromDerived.isRight()) {
return dataFromDerived.right().value();
}
Map<String, PropertyDataDefinition> propertiesAll = dataFromDerived.left().value();
-
Map<String, PropertyDataDefinition> properties = nodeType.getProperties();
-
if (properties != null) {
properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName());
p.setUniqueId(uid);
});
-
Either<Map<String, PropertyDataDefinition>, String> eitherMerged = ToscaDataDefinition.mergeDataMaps(propertiesAll, properties);
if (eitherMerged.isRight()) {
// TODO re-factor error handling - moving BL to operation resulted in loss of info about the invalid property
@@ -608,7 +603,8 @@ public abstract class ToscaElementOperation extends BaseOperation {
}
}
if (!propertiesAll.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES,
+ EdgeLabelEnum.PROPERTIES, propertiesAll);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -619,7 +615,8 @@ public abstract class ToscaElementOperation extends BaseOperation {
private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = nodeType.getAdditionalInformation();
if (additionalInformation != null) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
+ VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
@@ -627,12 +624,13 @@ public abstract class ToscaElementOperation extends BaseOperation {
return StorageOperationStatus.OK;
}
- protected <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> getDataFromDerived(List<GraphVertex> derivedResources, EdgeLabelEnum edge) {
+ protected <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> getDataFromDerived(List<GraphVertex> derivedResources,
+ EdgeLabelEnum edge) {
Map<String, T> propertiesAll = new HashMap<>();
-
if (derivedResources != null && !derivedResources.isEmpty()) {
for (GraphVertex derived : derivedResources) {
- Either<List<GraphVertex>, JanusGraphOperationStatus> derivedProperties = janusGraphDao.getChildrenVertices(derived, edge, JsonParseFlagEnum.ParseJson);
+ Either<List<GraphVertex>, JanusGraphOperationStatus> derivedProperties = janusGraphDao
+ .getChildrenVertices(derived, edge, JsonParseFlagEnum.ParseJson);
if (derivedProperties.isRight()) {
if (derivedProperties.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value());
@@ -684,7 +682,6 @@ public abstract class ToscaElementOperation extends BaseOperation {
protected JanusGraphOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) {
Map<String, String> allVersion = new HashMap<>();
-
allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId());
ArrayList<GraphVertex> allChildrenAndParants = new ArrayList<>();
Either<GraphVertex, JanusGraphOperationStatus> childResourceRes = janusGraphDao
@@ -692,11 +689,9 @@ public abstract class ToscaElementOperation extends BaseOperation {
while (childResourceRes.isLeft()) {
GraphVertex child = childResourceRes.left().value();
allChildrenAndParants.add(child);
- childResourceRes = janusGraphDao
- .getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ childResourceRes = janusGraphDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
}
JanusGraphOperationStatus operationStatus = childResourceRes.right().value();
-
if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) {
return operationStatus;
} else {
@@ -705,8 +700,7 @@ public abstract class ToscaElementOperation extends BaseOperation {
while (parentResourceRes.isLeft()) {
GraphVertex parent = parentResourceRes.left().value();
allChildrenAndParants.add(parent);
- parentResourceRes = janusGraphDao
- .getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ parentResourceRes = janusGraphDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
}
operationStatus = parentResourceRes.right().value();
if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) {
@@ -716,23 +710,24 @@ public abstract class ToscaElementOperation extends BaseOperation {
Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
return (isDeleted == null || !isDeleted);
}).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId()));
-
toscaElement.setAllVersions(allVersion);
return JanusGraphOperationStatus.OK;
}
}
}
- protected <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getFollowedComponent(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum neededType) {
-
+ protected <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getFollowedComponent(String userId,
+ Set<LifecycleStateEnum> lifecycleStates,
+ Set<LifecycleStateEnum> lastStateStates,
+ ComponentTypeEnum neededType) {
Map<GraphPropertyEnum, Object> props = null;
-
if (userId != null) {
props = new EnumMap<>(GraphPropertyEnum.class);
// for Designer retrieve specific user
props.put(GraphPropertyEnum.USERID, userId);
}
// in case of user id == null -> get all users by label
+
// for Tester and Admin retrieve all users
Either<List<GraphVertex>, JanusGraphOperationStatus> usersByCriteria = janusGraphDao
.getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse);
@@ -741,21 +736,19 @@ public abstract class ToscaElementOperation extends BaseOperation {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(usersByCriteria.right().value()));
}
GraphVertex userV = usersByCriteria.left().value().get(0);
-
List<T> components = new ArrayList<>();
List<T> componentsPerUser;
-
final Set<String> ids = new HashSet<>();
- Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = janusGraphDao.getChildrenVertices(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse);
+ Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = janusGraphDao
+ .getChildrenVertices(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse);
if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
- log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.STATE, childrenVertecies.right().value());
+ log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID),
+ EdgeLabelEnum.STATE, childrenVertecies.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value()));
}
-
// get all resource with current state
if (childrenVertecies.isLeft()) {
componentsPerUser = fetchComponents(userId, lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE);
-
if (componentsPerUser != null) {
for (T comp : componentsPerUser) {
ids.add(comp.getUniqueId());
@@ -766,66 +759,58 @@ public abstract class ToscaElementOperation extends BaseOperation {
// get all resource with last state
childrenVertecies = janusGraphDao.getChildrenVertices(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse);
if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
- log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value());
+ log.debug("Failed to fetch children vertices for user {} by edge {} error {}",
+ userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value()));
}
if (childrenVertecies.isLeft()) {
boolean isFirst;
- componentsPerUser = fetchComponents(userId, lastStateStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.LAST_STATE);
+ componentsPerUser = fetchComponents(userId, lastStateStates, childrenVertecies.left().value(), neededType,
+ EdgeLabelEnum.LAST_STATE);
if (componentsPerUser != null) {
for (T comp : componentsPerUser) {
isFirst = true;
-
if (ids.contains(comp.getUniqueId())) {
isFirst = false;
}
if (isFirst) {
components.add(comp);
}
-
}
}
}
}
-
} // whlile users
return Either.left(components);
}
- private <T extends ToscaElement> List<T> fetchComponents(String userId, Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices, ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) {
+ private <T extends ToscaElement> List<T> fetchComponents(String userId, Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices,
+ ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) {
List<T> components = new ArrayList<>();
for (GraphVertex node : vertices) {
-
Iterator<Edge> edges = node.getVertex().edges(Direction.IN, edgelabel.name());
while (edges.hasNext()) {
Edge edge = edges.next();
String stateStr = (String) janusGraphDao.getProperty(edge, EdgePropertyEnum.STATE);
-
LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr);
if (nodeState == null) {
log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId());
continue;
}
-
//get user from edge and compare to user from followed request
JanusGraphVertex userVertex = (JanusGraphVertex) edge.outVertex();
String userIdFromEdge = (String) janusGraphDao.getProperty(userVertex, GraphPropertyEnum.USERID.getProperty());
-
if (lifecycleStates != null && lifecycleStates.contains(nodeState) && (userIdFromEdge.equals(userId))) {
-
Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
Boolean isArchived = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED);
if (isDeleted != null && isDeleted || isArchived != null && isArchived) {
log.trace("Deleted/Archived element {}, discard", node.getUniqueId());
continue;
}
-
Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION);
if (isHighest) {
-
ComponentTypeEnum componentType = node.getType();
// get only latest versions
-
if (componentType == null) {
log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId());
continue;
@@ -846,16 +831,18 @@ public abstract class ToscaElementOperation extends BaseOperation {
log.debug("not supported node type {}", componentType);
break;
}// case
+
} // needed type
}
} // if
+
} // while edges
+
} // while resources
return components;
}
protected <T extends ToscaElement> void handleNode(List<T> components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) {
-
Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true));
if (component.isRight()) {
log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value());
@@ -864,7 +851,8 @@ public abstract class ToscaElementOperation extends BaseOperation {
}
}
- protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(String componentUid, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) {
+ protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(String componentUid, ComponentTypeEnum nodeType,
+ ComponentParametersView parametersFilter) {
Either<GraphVertex, JanusGraphOperationStatus> getVertexRes = janusGraphDao.getVertexById(componentUid);
if (getVertexRes.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexRes.right().value()));
@@ -872,19 +860,15 @@ public abstract class ToscaElementOperation extends BaseOperation {
return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter);
}
- protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) {
-
+ protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType,
+ ComponentParametersView parametersFilter) {
log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId());
-
janusGraphDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata);
-
T toscaElement = convertToComponent(vertexComponent);
-
JanusGraphOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
status = setLastModifierFromGraph(vertexComponent, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
@@ -930,11 +914,10 @@ public abstract class ToscaElementOperation extends BaseOperation {
log.debug("Not supported tosca type {}", label);
break;
}
-
if (toscaElement != null) {
final Map<String, Object> jsonMetada = componentV.getMetadataJson();
if (MapUtils.isNotEmpty(jsonMetada)) {
- toscaElement.setMetadata(jsonMetada);
+ toscaElement.setMetadata(jsonMetada);
final Object toscaVersion = jsonMetada.get(ToscaTagNamesEnum.TOSCA_VERSION.getElementName());
if (toscaVersion != null) {
toscaElement.setToscaVersion((String) toscaVersion);
@@ -942,15 +925,12 @@ public abstract class ToscaElementOperation extends BaseOperation {
final Object dataTypes = jsonMetada.get(ToscaTagNamesEnum.DATA_TYPES.getElementName());
if (dataTypes != null) {
final Map<String, DataTypeDataDefinition> dataTypeDefinitionMap = new HashMap<>();
-
final Map<String, Object> toscaAttributes = (Map<String, Object>) dataTypes;
-
for (final Entry<String, Object> attributeNameValue : toscaAttributes.entrySet()) {
final Object value = attributeNameValue.getValue();
final String key = attributeNameValue.getKey();
if (value instanceof Map) {
- final DataTypeDefinition dataTypeDefinition =
- createDataTypeDefinitionWithName(attributeNameValue);
+ final DataTypeDefinition dataTypeDefinition = createDataTypeDefinitionWithName(attributeNameValue);
dataTypeDefinitionMap.put(dataTypeDefinition.getName(), dataTypeDefinition);
} else {
dataTypeDefinitionMap.put(key, createDataType(String.valueOf(value)));
@@ -963,44 +943,14 @@ public abstract class ToscaElementOperation extends BaseOperation {
return (T) toscaElement;
}
- public static DataTypeDefinition createDataType(final String dataTypeName) {
- final DataTypeDefinition dataType = new DataTypeDefinition();
- dataType.setName(dataTypeName);
- return dataType;
- }
-
- public static DataTypeDefinition createDataTypeDefinitionWithName(final Entry<String, Object> attributeNameValue) {
- final Map<String, Object> attributeMap = (Map<String, Object>) attributeNameValue.getValue();
- final DataTypeDefinition dataType = createDataType(attributeNameValue.getKey());
- setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, dataType::setDescription);
- setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM_NAME, dataType::setDerivedFromName);
- // TODO - find the way to set the properties
-// CommonImportManager.setProperties(attributeMap, dataType::setProperties);
- final Object derivedFrom = attributeMap.get(JsonPresentationFields.DERIVED_FROM.getPresentation());
- if (derivedFrom instanceof Map) {
- final Map<String, Object> derivedFromMap = (Map<String, Object>) derivedFrom;
- final DataTypeDefinition parentDataTypeDataDefinition = new DataTypeDefinition();
- parentDataTypeDataDefinition
- .setName((String) derivedFromMap.get(JsonPresentationFields.NAME.getPresentation()));
- parentDataTypeDataDefinition
- .setUniqueId((String) derivedFromMap.get(JsonPresentationFields.UNIQUE_ID.getPresentation()));
- parentDataTypeDataDefinition
- .setCreationTime((Long) derivedFromMap.get(JsonPresentationFields.CREATION_TIME.getPresentation()));
- parentDataTypeDataDefinition.setModificationTime(
- (Long) derivedFromMap.get(JsonPresentationFields.MODIFICATION_TIME.getPresentation()));
- dataType.setDerivedFrom(parentDataTypeDataDefinition);
- }
- return dataType;
- }
-
protected JanusGraphOperationStatus setResourceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) {
List<CategoryDefinition> categories = new ArrayList<>();
SubCategoryDefinition subcategory;
-
Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao
.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
- log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value());
+ log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(),
+ childVertex.right().value());
return childVertex.right().value();
}
Vertex subCategoryV = childVertex.left().value();
@@ -1010,16 +960,14 @@ public abstract class ToscaElementOperation extends BaseOperation {
subcategory.setUniqueId((String) subCategoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
subcategory.setNormalizedName(subCategoryNormalizedName);
subcategory.setName((String) subCategoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
-
Type listTypeSubcat = new TypeToken<List<MetadataKeyDataDefinition>>() {
}.getType();
- List<MetadataKeyDataDefinition> metadataKeys =
- subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson().fromJson(
- (String) subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(),
- listTypeSubcat) : Collections.emptyList();
+ List<MetadataKeyDataDefinition> metadataKeys = subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson()
+ .fromJson((String) subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(), listTypeSubcat)
+ : Collections.emptyList();
subcategory.setMetadataKeys(metadataKeys);
-
- Either<Vertex, JanusGraphOperationStatus> parentVertex = janusGraphDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
+ Either<Vertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
+ .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
Vertex categoryV = parentVertex.left().value();
String categoryNormalizedName = (String) categoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
catalogComponent.setCategoryNormalizedName(categoryNormalizedName);
@@ -1027,7 +975,6 @@ public abstract class ToscaElementOperation extends BaseOperation {
category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
category.setNormalizedName(categoryNormalizedName);
category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
-
category.addSubCategory(subcategory);
categories.add(category);
catalogComponent.setCategories(categories);
@@ -1036,9 +983,11 @@ public abstract class ToscaElementOperation extends BaseOperation {
protected JanusGraphOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) {
List<CategoryDefinition> categories = new ArrayList<>();
- Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
+ Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao
+ .getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
- log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value());
+ log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(),
+ childVertex.right().value());
return childVertex.right().value();
}
Vertex categoryV = childVertex.left().value();
@@ -1048,16 +997,13 @@ public abstract class ToscaElementOperation extends BaseOperation {
category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
category.setNormalizedName(categoryNormalizedName);
category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
- category.setUseServiceSubstitutionForNestedServices((Boolean) categoryV.property(GraphPropertyEnum.USE_SUBSTITUTION_FOR_NESTED_SERVICES.getProperty()).orElse(false));
-
+ category.setUseServiceSubstitutionForNestedServices(
+ (Boolean) categoryV.property(GraphPropertyEnum.USE_SUBSTITUTION_FOR_NESTED_SERVICES.getProperty()).orElse(false));
Type listTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
}.getType();
- List<MetadataKeyDataDefinition> metadataKeys =
- categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson().fromJson(
- (String) categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(), listTypeCat)
- : Collections.emptyList();
+ List<MetadataKeyDataDefinition> metadataKeys = categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson()
+ .fromJson((String) categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(), listTypeCat) : Collections.emptyList();
category.setMetadataKeys(metadataKeys);
-
categories.add(category);
catalogComponent.setCategories(categories);
return JanusGraphOperationStatus.OK;
@@ -1066,7 +1012,6 @@ public abstract class ToscaElementOperation extends BaseOperation {
protected JanusGraphOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
List<CategoryDefinition> categories = new ArrayList<>();
SubCategoryDefinition subcategory;
-
Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
@@ -1079,52 +1024,47 @@ public abstract class ToscaElementOperation extends BaseOperation {
subcategory.setUniqueId(subCategoryV.getUniqueId());
subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
-
Type listTypeSubcat = new TypeToken<List<String>>() {
}.getType();
List<String> iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat);
subcategory.setIcons(iconsfromJsonSubcat);
-
- final Type metadataKeysTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {}.getType();
- final List<MetadataKeyDataDefinition> metadataKeysfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.METADATA_KEYS), metadataKeysTypeCat);
+ final Type metadataKeysTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
+ }.getType();
+ final List<MetadataKeyDataDefinition> metadataKeysfromJsonCat = getGson()
+ .fromJson((String) metadataProperties.get(GraphPropertyEnum.METADATA_KEYS), metadataKeysTypeCat);
subcategory.setMetadataKeys(metadataKeysfromJsonCat);
-
Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
if (parentVertex.isRight()) {
- log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value());
+ log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(),
+ parentVertex.right().value());
return childVertex.right().value();
}
GraphVertex categoryV = parentVertex.left().value();
metadataProperties = categoryV.getMetadataProperties();
-
CategoryDefinition category = new CategoryDefinition();
category.setUniqueId(categoryV.getUniqueId());
category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
-
Type listTypeCat = new TypeToken<List<String>>() {
}.getType();
List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat);
category.setIcons(iconsfromJsonCat);
-
category.addSubCategory(subcategory);
categories.add(category);
toscaElement.setCategories(categories);
-
return JanusGraphOperationStatus.OK;
}
- public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV, ComponentParametersView filterResult) {
+ public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV,
+ ComponentParametersView filterResult) {
Either<T, StorageOperationStatus> result = null;
-
log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId()));
if (toscaElementToUpdate == null) {
log.error("Service object is null");
result = Either.right(StorageOperationStatus.BAD_REQUEST);
return result;
}
-
String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId();
if (modifierUserId == null || modifierUserId.isEmpty()) {
log.error("UserId is missing in the request.");
@@ -1132,16 +1072,13 @@ public abstract class ToscaElementOperation extends BaseOperation {
return result;
}
Either<GraphVertex, JanusGraphOperationStatus> findUser = findUserVertex(modifierUserId);
-
if (findUser.isRight()) {
JanusGraphOperationStatus status = findUser.right().value();
log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, modifierUserId, status);
return result;
}
-
GraphVertex modifierV = findUser.left().value();
String toscaElementId = toscaElementToUpdate.getUniqueId();
-
Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
.getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
if (parentVertex.isRight()) {
@@ -1150,9 +1087,7 @@ public abstract class ToscaElementOperation extends BaseOperation {
}
GraphVertex userV = parentVertex.left().value();
String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
-
String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
-
if (currentModifier.equals(modifierUserId)) {
log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier.");
} else {
@@ -1164,49 +1099,43 @@ public abstract class ToscaElementOperation extends BaseOperation {
return result;
}
}
-
final long currentTimeMillis = System.currentTimeMillis();
- log.debug("Going to update the last Update Date of the resource from {} to {}", elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis);
+ log.debug("Going to update the last Update Date of the resource from {} to {}",
+ elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis);
elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis);
-
StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV);
if (checkCategories != StorageOperationStatus.OK) {
result = Either.right(checkCategories);
return result;
}
-
// update all data on vertex
fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata);
-
Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(elementV);
-
if (updateElement.isRight()) {
log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
return result;
}
GraphVertex updateElementV = updateElement.left().value();
-
// DE230195 in case resource name changed update TOSCA artifacts
+
// file names accordingly
String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
if (newSystemName != null && !newSystemName.equals(prevSystemName)) {
- Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> resultToscaArt = getDataFromGraph(updateElementV, EdgeLabelEnum.TOSCA_ARTIFACTS);
+ Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> resultToscaArt = getDataFromGraph(updateElementV,
+ EdgeLabelEnum.TOSCA_ARTIFACTS);
if (resultToscaArt.isRight()) {
log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resultToscaArt.right().value()));
}
-
Map<String, ArtifactDataDefinition> toscaArtifacts = resultToscaArt.left().value();
if (toscaArtifacts != null) {
for (Entry<String, ArtifactDataDefinition> artifact : toscaArtifacts.entrySet()) {
generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue());
}
// TODO call to new Artifact operation in order to update list of artifacts
-
}
}
-
if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) {
StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV);
if (resultDerived != StorageOperationStatus.OK) {
@@ -1214,33 +1143,30 @@ public abstract class ToscaElementOperation extends BaseOperation {
return Either.right(resultDerived);
}
}
-
Either<T, StorageOperationStatus> updatedResource = getToscaElement(updateElementV, filterResult);
if (updatedResource.isRight()) {
log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value());
result = Either.right(StorageOperationStatus.BAD_REQUEST);
return result;
}
-
T updatedResourceValue = updatedResource.left().value();
result = Either.left(updatedResourceValue);
-
return result;
}
protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) {
- return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- janusGraphDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN));
+ return DaoStatusConverter
+ .convertJanusGraphStatusToStorageStatus(janusGraphDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN));
}
protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) {
- return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- janusGraphDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT));
+ return DaoStatusConverter
+ .convertJanusGraphStatusToStorageStatus(janusGraphDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT));
}
private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) {
- Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel()))
- .findAny().get().getValue();
+ Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()
+ .entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())).findAny().get().getValue();
artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName"));
}
@@ -1248,7 +1174,6 @@ public abstract class ToscaElementOperation extends BaseOperation {
StorageOperationStatus status = StorageOperationStatus.OK;
List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories();
CategoryDefinition newCategory = newCategoryList.get(0);
-
Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
@@ -1258,19 +1183,17 @@ public abstract class ToscaElementOperation extends BaseOperation {
GraphVertex subCategoryV = childVertex.left().value();
Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
-
Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
if (parentVertex.isRight()) {
- log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value());
+ log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(),
+ parentVertex.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value());
}
GraphVertex categoryV = parentVertex.left().value();
metadataProperties = categoryV.getMetadataProperties();
String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
-
boolean categoryWasChanged = false;
-
String newCategoryName = newCategory.getName();
SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0);
String newSubCategoryName = newSubcategory.getName();
@@ -1285,8 +1208,8 @@ public abstract class ToscaElementOperation extends BaseOperation {
}
}
if (categoryWasChanged) {
- Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName, newCategoryName);
-
+ Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName,
+ newCategoryName);
if (getCategoryVertex.isRight()) {
return getCategoryVertex.right().value();
}
@@ -1297,14 +1220,15 @@ public abstract class ToscaElementOperation extends BaseOperation {
return status;
}
- public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, boolean isHighestVersions) {
+ public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType,
+ List<ResourceTypeEnum> excludeTypes,
+ boolean isHighestVersions) {
Either<List<GraphVertex>, JanusGraphOperationStatus> listOfComponents;
if (isHighestVersions) {
listOfComponents = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.NoParse);
} else {
listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes);
}
-
if (listOfComponents.isRight() && listOfComponents.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(listOfComponents.right().value()));
}
@@ -1313,7 +1237,8 @@ public abstract class ToscaElementOperation extends BaseOperation {
List<GraphVertex> highestAndAllCertified = listOfComponents.left().value();
if (highestAndAllCertified != null && !highestAndAllCertified.isEmpty()) {
for (GraphVertex vertexComponent : highestAndAllCertified) {
- Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true));
+ Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType,
+ new ComponentParametersView(true));
if (component.isRight()) {
log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
return Either.right(component.right().value());
@@ -1329,7 +1254,6 @@ public abstract class ToscaElementOperation extends BaseOperation {
public Either<List<CatalogComponent>, StorageOperationStatus> getElementCatalogData(boolean isCatalog, List<ResourceTypeEnum> excludeTypes) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
-
Map<String, CatalogComponent> existInCatalog = new HashMap<>();
Either<Iterator<Vertex>, JanusGraphOperationStatus> verticesEither = janusGraphDao.getCatalogOrArchiveVerticies(isCatalog);
if (verticesEither.isRight()) {
@@ -1349,22 +1273,19 @@ public abstract class ToscaElementOperation extends BaseOperation {
VertexProperty<Object> property = vertex.property(GraphPropertiesDictionary.METADATA.getProperty());
String json = (String) property.value();
Map<String, Object> metadatObj = JsonParserUtils.toMap(json);
-
String uniqueId = (String) metadatObj.get(JsonPresentationFields.UNIQUE_ID.getPresentation());
Boolean isDeleted = (Boolean) metadatObj.get(JsonPresentationFields.IS_DELETED.getPresentation());
-
-
if (isAddToCatalog(excludeTypes, metadatObj) && (existInCatalog.get(uniqueId) == null && (isDeleted == null || !isDeleted.booleanValue()))) {
CatalogComponent catalogComponent = new CatalogComponent();
catalogComponent.setUniqueId(uniqueId);
-
- catalogComponent.setComponentType(ComponentTypeEnum.valueOf((String) metadatObj.get(JsonPresentationFields.COMPONENT_TYPE.getPresentation())));
+ catalogComponent
+ .setComponentType(ComponentTypeEnum.valueOf((String) metadatObj.get(JsonPresentationFields.COMPONENT_TYPE.getPresentation())));
catalogComponent.setVersion((String) metadatObj.get(JsonPresentationFields.VERSION.getPresentation()));
catalogComponent.setName((String) metadatObj.get(JsonPresentationFields.NAME.getPresentation()));
catalogComponent.setIcon((String) metadatObj.get(JsonPresentationFields.ICON.getPresentation()));
catalogComponent.setLifecycleState((String) metadatObj.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation()));
Object lastUpdateDate = metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation());
- catalogComponent.setLastUpdateDate( (lastUpdateDate != null ? (Long)lastUpdateDate : 0L));
+ catalogComponent.setLastUpdateDate((lastUpdateDate != null ? (Long) lastUpdateDate : 0L));
catalogComponent.setDistributionStatus((String) metadatObj.get(JsonPresentationFields.DISTRIBUTION_STATUS.getPresentation()));
catalogComponent.setDescription((String) metadatObj.get(JsonPresentationFields.DESCRIPTION.getPresentation()));
catalogComponent.setSystemName((String) metadatObj.get(JsonPresentationFields.SYSTEM_NAME.getPresentation()));
@@ -1372,17 +1293,16 @@ public abstract class ToscaElementOperation extends BaseOperation {
catalogComponent.setInvariantUUID((String) metadatObj.get(JsonPresentationFields.INVARIANT_UUID.getPresentation()));
catalogComponent.setIsHighestVersion((Boolean) metadatObj.get(JsonPresentationFields.HIGHEST_VERSION.getPresentation()));
Iterator<Edge> edges = vertex.edges(Direction.IN, EdgeLabelEnum.STATE.name());
- if(edges.hasNext()){
- catalogComponent.setLastUpdaterUserId((String) edges.next().outVertex().property(GraphPropertiesDictionary.USERID.getProperty()).value());
+ if (edges.hasNext()) {
+ catalogComponent
+ .setLastUpdaterUserId((String) edges.next().outVertex().property(GraphPropertiesDictionary.USERID.getProperty()).value());
}
Object resourceType = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation());
if (resourceType != null) {
catalogComponent.setResourceType((String) resourceType);
}
-
if (catalogComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
setServiceCategoryFromGraphV(vertex, catalogComponent);
-
} else {
setResourceCategoryFromGraphV(vertex, catalogComponent);
}
@@ -1409,30 +1329,28 @@ public abstract class ToscaElementOperation extends BaseOperation {
return isAddToCatalog;
}
- public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestComponents(ComponentTypeEnum
- componentType, List<ResourceTypeEnum> excludeTypes, JsonParseFlagEnum parseFlag) {
+ public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType,
+ List<ResourceTypeEnum> excludeTypes,
+ JsonParseFlagEnum parseFlag) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
if (componentType == ComponentTypeEnum.RESOURCE) {
propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false);
propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
}
propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
propertiesHasNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
-
- return janusGraphDao
- .getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag);
+ return janusGraphDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag);
}
// highest + (certified && !highest)
- public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestAndAllCertifiedComponents
- (ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) {
+ public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType,
+ List<ResourceTypeEnum> excludeTypes) {
long startFetchAllStates = System.currentTimeMillis();
- Either<List<GraphVertex>, JanusGraphOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.ParseMetadata);
-
+ Either<List<GraphVertex>, JanusGraphOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes,
+ JsonParseFlagEnum.ParseMetadata);
Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new EnumMap<>(GraphPropertyEnum.class);
propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
@@ -1441,43 +1359,32 @@ public abstract class ToscaElementOperation extends BaseOperation {
propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false);
propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
}
-
propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true);
propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
Either<List<GraphVertex>, JanusGraphOperationStatus> certifiedNotHighestNodes = janusGraphDao
.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata);
if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
return Either.right(certifiedNotHighestNodes.right().value());
}
-
long endFetchAllStates = System.currentTimeMillis();
-
List<GraphVertex> allNodes = new ArrayList<>();
-
if (certifiedNotHighestNodes.isLeft()) {
allNodes.addAll(certifiedNotHighestNodes.left().value());
}
if (highestNodes.isLeft()) {
allNodes.addAll(highestNodes.left().value());
}
-
log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates);
return Either.left(allNodes);
}
- protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum
- componentType) {
-
+ protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
// get all components marked for delete
Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
props.put(GraphPropertyEnum.IS_DELETED, true);
props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
-
- Either<List<GraphVertex>, JanusGraphOperationStatus> componentsToDelete = janusGraphDao
- .getByCriteria(null, props, JsonParseFlagEnum.NoParse);
-
+ Either<List<GraphVertex>, JanusGraphOperationStatus> componentsToDelete = janusGraphDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse);
if (componentsToDelete.isRight()) {
JanusGraphOperationStatus error = componentsToDelete.right().value();
if (error.equals(JanusGraphOperationStatus.NOT_FOUND)) {
@@ -1491,9 +1398,9 @@ public abstract class ToscaElementOperation extends BaseOperation {
return Either.left(componentsToDelete.left().value());
}
- protected JanusGraphOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement
- toscaElement) {
- Either<Map<String, AdditionalInfoParameterDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ADDITIONAL_INFORMATION);
+ protected JanusGraphOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
+ Either<Map<String, AdditionalInfoParameterDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
+ EdgeLabelEnum.ADDITIONAL_INFORMATION);
if (result.isLeft()) {
toscaElement.setAdditionalInformation(result.left().value());
} else {
@@ -1505,34 +1412,25 @@ public abstract class ToscaElementOperation extends BaseOperation {
}
// --------------------------------------------
- public abstract <T extends
- ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView);
-
- public abstract <T extends
- ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView);
+ public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId,
+ ComponentParametersView componentParametersView);
- public abstract <T extends
- ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex);
+ public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex,
+ ComponentParametersView componentParametersView);
- public abstract <T extends
- ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement);
+ public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex);
- protected abstract <T extends ToscaElement> JanusGraphOperationStatus
- setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement);
+ public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement);
- protected abstract <T extends ToscaElement> JanusGraphOperationStatus
- setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement);
+ protected abstract <T extends ToscaElement> JanusGraphOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement);
- protected abstract <T extends ToscaElement> JanusGraphOperationStatus
- setRequirementsFromGraph(GraphVertex componentV, T toscaElement);
+ protected abstract <T extends ToscaElement> JanusGraphOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement);
- protected abstract <T extends ToscaElement> StorageOperationStatus
- validateCategories(T toscaElementToUpdate, GraphVertex elementV);
+ protected abstract <T extends ToscaElement> JanusGraphOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement);
- protected abstract <T extends ToscaElement> StorageOperationStatus
- updateDerived(T toscaElementToUpdate, GraphVertex updateElementV);
+ protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV);
- public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T
- toscaElementToUpdate, JsonParseFlagEnum flag);
+ protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV);
+ public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java
index c5b82dc295..3858912660 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import static java.util.Objects.requireNonNull;
@@ -126,12 +125,12 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
-
@org.springframework.stereotype.Component("tosca-operation-facade")
public class ToscaOperationFacade {
+ // region - ToscaElement - GetById
+ public static final String PROXY_SUFFIX = "_proxy";
// region - Fields
-
private static final String COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch a component with and UniqueId {}, error: {}";
private static final String FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS = "Failed to find recently added property {} on the resource {}. Status is {}. ";
private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. ";
@@ -140,6 +139,7 @@ public class ToscaOperationFacade {
private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!";
private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}";
+ private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName());
@Autowired
private NodeTypeOperation nodeTypeOperation;
@Autowired
@@ -150,14 +150,23 @@ public class ToscaOperationFacade {
private GroupsOperation groupsOperation;
@Autowired
private HealingJanusGraphDao janusGraphDao;
+ // endregion
@Autowired
private ContainerInstanceTypesData containerInstanceTypesData;
- private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName());
- // endregion
-
- // region - ToscaElement - GetById
- public static final String PROXY_SUFFIX = "_proxy";
+ private static Optional<CapabilityDefinition> getPropertyCapability(String propertyParentUniqueId, Component containerComponent) {
+ Map<String, List<CapabilityDefinition>> componentCapabilities = containerComponent.getCapabilities();
+ if (MapUtils.isEmpty(componentCapabilities)) {
+ return Optional.empty();
+ }
+ List<CapabilityDefinition> 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))
+ .findAny();
+ }
public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
ComponentParametersView filters = new ComponentParametersView();
@@ -167,31 +176,23 @@ public class ToscaOperationFacade {
}
public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
-
return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
-
}
public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, filters.detectParseFlag());
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, filters.detectParseFlag());
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
}
return getToscaElementByOperation(getVertexEither.left().value(), filters);
}
public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, parseFlag);
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, parseFlag);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
}
return getToscaElementByOperation(getVertexEither.left().value());
}
@@ -201,9 +202,7 @@ public class ToscaOperationFacade {
}
public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
JanusGraphOperationStatus status = getVertexEither.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -215,42 +214,38 @@ public class ToscaOperationFacade {
}
return Either.left(true);
}
+ // endregion
public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
props.put(GraphPropertyEnum.UUID, component.getUUID());
props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
Either<List<GraphVertex>, JanusGraphOperationStatus> getVertexEither = janusGraphDao
.getByCriteria(ModelConverter.getVertexType(component), props);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
}
return getToscaElementByOperation(getVertexEither.left().value().get(0));
}
- // endregion
// region - ToscaElement - GetByOperation
private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
return getToscaElementByOperation(componentV, new ComponentParametersView());
}
private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV,
- ComponentParametersView filters) {
+ ComponentParametersView filters) {
if (componentV == null) {
log.debug("Unexpected null value for `componentV`");
return Either.right(StorageOperationStatus.GENERAL_ERROR);
} else {
VertexTypeEnum label = componentV.getLabel();
-
ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
if (toscaOperation != null) {
log.debug("getToscaElementByOperation: toscaOperation={}", toscaOperation.getClass());
}
-
Either<ToscaElement, StorageOperationStatus> toscaElement;
String componentId = componentV.getUniqueId();
if (toscaOperation != null) {
@@ -279,7 +274,6 @@ public class ToscaOperationFacade {
public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
-
ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
if (createToscaElement.isLeft()) {
@@ -292,23 +286,17 @@ public class ToscaOperationFacade {
// region - ToscaElement Delete
public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
-
- if (Boolean.TRUE.equals(componentToDelete.getIsDeleted())
- && Boolean.FALSE.equals(componentToDelete.isHighestVersion())) {
+ if (Boolean.TRUE.equals(componentToDelete.getIsDeleted()) && Boolean.FALSE.equals(componentToDelete.isHighestVersion())) {
// component already marked for delete
return StorageOperationStatus.OK;
} else {
-
Either<GraphVertex, JanusGraphOperationStatus> getResponse = janusGraphDao
.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
if (getResponse.isRight()) {
- log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(),
- getResponse.right().value());
+ log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value());
-
}
GraphVertex componentV = getResponse.left().value();
-
// same operation for node type and topology template operations
Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
if (result.isRight()) {
@@ -319,13 +307,10 @@ public class ToscaOperationFacade {
}
public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (getVertexEither.isRight()) {
log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
}
Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
if (deleteElement.isRight()) {
@@ -333,7 +318,6 @@ public class ToscaOperationFacade {
return Either.right(deleteElement.right().value());
}
T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
-
return Either.left(dataModel);
}
@@ -357,8 +341,8 @@ public class ToscaOperationFacade {
}
return toscaElement;
}
- // endregion
+ // endregion
private ToscaElementOperation getToscaElementOperation(Component component) {
return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
}
@@ -376,17 +360,13 @@ public class ToscaOperationFacade {
public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
return getLatestByName(GraphPropertyEnum.NAME, resourceName);
-
}
public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) {
-
Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
-
Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
-
if (resources.isRight()) {
if (resources.right().value() == JanusGraphOperationStatus.NOT_FOUND) {
return StorageOperationStatus.OK;
@@ -396,17 +376,17 @@ public class ToscaOperationFacade {
}
}
return StorageOperationStatus.ENTITY_ALREADY_EXISTS;
-
}
- public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
+ public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates,
+ Set<LifecycleStateEnum> lastStateStates,
+ ComponentTypeEnum componentType) {
Either<List<ToscaElement>, StorageOperationStatus> followedResources;
if (componentType == ComponentTypeEnum.RESOURCE) {
followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
} else {
followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
}
-
Set<T> components = new HashSet<>();
if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
return Either.right(followedResources.right().value());
@@ -422,140 +402,119 @@ public class ToscaOperationFacade {
}
public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
-
return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
}
-
- public Either<Resource, StorageOperationStatus> getByToscaResourceNameMatchingVendorRelease(final String toscaResourceName, final String vendorVersion) {
- return getByToscaResourceNameMatchingVendorRelease(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata, vendorVersion);
+ public Either<Resource, StorageOperationStatus> getByToscaResourceNameMatchingVendorRelease(final String toscaResourceName,
+ final String vendorVersion) {
+ return getByToscaResourceNameMatchingVendorRelease(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata,
+ vendorVersion);
}
-
- public Either<Resource, StorageOperationStatus> getByToscaResourceNameMatchingVendorRelease(String toscaResourceName,
- VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag, String vendorRelease) {
-
- Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
- props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
- props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
-
- Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
-
- Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao
- .getByCriteria(vertexType, props, null, predicateCriteria, parseFlag);
-
- if(getLatestRes.isRight() || CollectionUtils.isEmpty(getLatestRes.left().value())) {
- getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
- }
-
- return getLatestRes
- .right().map(
- status -> {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ",
- vertexType, toscaResourceName, status);
- return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
- }
- )
- .left().bind(
- resources -> {
- double version = 0.0;
- GraphVertex highestResource = null;
- for (GraphVertex resource : resources) {
- double resourceVersion = Double
- .parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
- if (resourceVersion > version && isValidForVendorRelease(resource, vendorRelease)) {
- version = resourceVersion;
- highestResource = resource;
- }
- }
- if (highestResource != null) {
- return getToscaFullElement(highestResource.getUniqueId());
- } else {
- log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- }
- );
- }
-
- private Map<String, Entry<JanusGraphPredicate, Object>> getVendorVersionPredicate(final String vendorRelease) {
- Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = new HashMap<>();
- if (!"1.0".equals(vendorRelease)) {
- String[] vendorReleaseElements = vendorRelease.split("\\.");
- if (vendorReleaseElements.length > 0) {
- String regex = ".*\"vendorRelease\":\"";
- for (int i = 0; i < vendorReleaseElements.length; i++) {
- regex += vendorReleaseElements[i];
- regex += i < vendorReleaseElements.length - 1 ? "\\." : "\".*";
- }
- predicateCriteria.put("metadata", new HashMap.SimpleEntry<>(REGEX, regex));
- }
- }
- return predicateCriteria;
- }
-
- private boolean isValidForVendorRelease(final GraphVertex resource, final String vendorRelease) {
- if (!vendorRelease.equals("1.0")) {
- try {
- Semver resourceSemVer = new Semver((String)resource.getJsonMetadataField(JsonPresentationFields.VENDOR_RELEASE), SemverType.NPM);
- Semver packageSemVer = new Semver(vendorRelease, SemverType.NPM);
- return !resourceSemVer.isGreaterThan(packageSemVer);
- } catch (Exception exception) {
- log.debug("Error in comparing vendor release", exception);
- return true;
- }
- }
- return true;
- }
-
- public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName,
- VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
+ public Either<Resource, StorageOperationStatus> getByToscaResourceNameMatchingVendorRelease(String toscaResourceName, VertexTypeEnum vertexType,
+ JsonParseFlagEnum parseFlag, String vendorRelease) {
Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
- props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao
- .getByCriteria(vertexType, props, parseFlag);
-
- return getLatestRes
- .right().map(
- status -> {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ",
- vertexType, toscaResourceName, status);
- return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
+ .getByCriteria(vertexType, props, null, predicateCriteria, parseFlag);
+ if (getLatestRes.isRight() || CollectionUtils.isEmpty(getLatestRes.left().value())) {
+ getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
+ }
+ return getLatestRes.right().map(status -> {
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
+ return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
+ }).left().bind(resources -> {
+ double version = 0.0;
+ GraphVertex highestResource = null;
+ for (GraphVertex resource : resources) {
+ double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
+ if (resourceVersion > version && isValidForVendorRelease(resource, vendorRelease)) {
+ version = resourceVersion;
+ highestResource = resource;
}
- )
- .left().bind(
- resources -> {
- double version = 0.0;
- GraphVertex highestResource = null;
- for (GraphVertex resource : resources) {
- double resourceVersion = Double
- .parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
- if (resourceVersion > version) {
- version = resourceVersion;
- highestResource = resource;
- }
- }
- if (highestResource != null) {
- return getToscaFullElement(highestResource.getUniqueId());
- } else {
- log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
+ }
+ if (highestResource != null) {
+ return getToscaFullElement(highestResource.getUniqueId());
+ } else {
+ log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ });
+ }
+
+ private Map<String, Entry<JanusGraphPredicate, Object>> getVendorVersionPredicate(final String vendorRelease) {
+ Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = new HashMap<>();
+ if (!"1.0".equals(vendorRelease)) {
+ String[] vendorReleaseElements = vendorRelease.split("\\.");
+ if (vendorReleaseElements.length > 0) {
+ String regex = ".*\"vendorRelease\":\"";
+ for (int i = 0; i < vendorReleaseElements.length; i++) {
+ regex += vendorReleaseElements[i];
+ regex += i < vendorReleaseElements.length - 1 ? "\\." : "\".*";
}
- );
+ predicateCriteria.put("metadata", new HashMap.SimpleEntry<>(REGEX, regex));
+ }
+ }
+ return predicateCriteria;
}
-
- public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName) {
- if (toscaResourceName != null && toscaResourceName.contains("org.openecomp.resource.vf"))
- return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.ParseMetadata);
- else
- return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
+
+ private boolean isValidForVendorRelease(final GraphVertex resource, final String vendorRelease) {
+ if (!vendorRelease.equals("1.0")) {
+ try {
+ Semver resourceSemVer = new Semver((String) resource.getJsonMetadataField(JsonPresentationFields.VENDOR_RELEASE), SemverType.NPM);
+ Semver packageSemVer = new Semver(vendorRelease, SemverType.NPM);
+ return !resourceSemVer.isGreaterThan(packageSemVer);
+ } catch (Exception exception) {
+ log.debug("Error in comparing vendor release", exception);
+ return true;
+ }
+ }
+ return true;
}
- public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
+ public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType,
+ JsonParseFlagEnum parseFlag) {
+ Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
+ props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
+ return getLatestRes.right().map(status -> {
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
+ return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
+ }).left().bind(resources -> {
+ double version = 0.0;
+ GraphVertex highestResource = null;
+ for (GraphVertex resource : resources) {
+ double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
+ if (resourceVersion > version) {
+ version = resourceVersion;
+ highestResource = resource;
+ }
+ }
+ if (highestResource != null) {
+ return getToscaFullElement(highestResource.getUniqueId());
+ } else {
+ log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ });
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName) {
+ if (toscaResourceName != null && toscaResourceName.contains("org.openecomp.resource.vf")) {
+ return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.ParseMetadata);
+ } else {
+ return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
+ }
+ }
+ public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType,
+ JsonParseFlagEnum parseFlag) {
Either<Resource, StorageOperationStatus> result = null;
Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
@@ -563,12 +522,11 @@ public class ToscaOperationFacade {
if (!toscaResourceName.contains("org.openecomp.resource.vf")) {
props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
}
-
Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
-
if (getLatestRes.isRight()) {
JanusGraphOperationStatus status = getLatestRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
if (result == null) {
@@ -582,7 +540,6 @@ public class ToscaOperationFacade {
highestResource = resource;
}
}
-
if (highestResource != null) {
result = getToscaFullElement(highestResource.getUniqueId());
} else {
@@ -601,41 +558,44 @@ public class ToscaOperationFacade {
return validateUniquenessRes;
}
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId,
+ RequirementCapabilityRelDef requirementDef) {
return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
}
/**
* Allows to get fulfilled requirement by relation and received predicate
*/
- public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
+ public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId,
+ RequirementCapabilityRelDef relation,
+ BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate);
}
/**
* Allows to get fulfilled capability by relation and received predicate
*/
- public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
+ public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId,
+ RequirementCapabilityRelDef relation,
+ BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
}
- public Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId, List<RequirementCapabilityRelDef> relations) {
- Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> reqAndCapListEither = nodeTemplateOperation.associateResourceInstances(component, componentId, relations);
+ public Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId,
+ List<RequirementCapabilityRelDef> relations) {
+ Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> reqAndCapListEither = nodeTemplateOperation
+ .associateResourceInstances(component, componentId, relations);
if (component != null) {
updateInstancesCapAndReqOnComponentFromDB(component);
}
return reqAndCapListEither;
-
}
protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
-
Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
-
Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
-
if (resources.isRight() && resources.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("failed to get resources from graph with property name: {}", name);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value()));
@@ -654,15 +614,11 @@ public class ToscaOperationFacade {
log.debug("resources with property name:{} does not exists in graph", name);
return Either.left(true);
}
-
}
// region - Component Update
-
public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
-
copyArtifactsToNewComponent(newComponent, oldComponent);
-
Either<GraphVertex, JanusGraphOperationStatus> componentVEither = janusGraphDao
.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
if (componentVEither.isRight()) {
@@ -670,12 +626,12 @@ public class ToscaOperationFacade {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(componentVEither.right().value()));
}
GraphVertex componentv = componentVEither.left().value();
- Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
+ .getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
if (parentVertexEither.isRight() && parentVertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("Failed to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertexEither.right().value()));
}
-
Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
if (deleteToscaComponent.isRight()) {
log.debug("Failed to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
@@ -695,9 +651,11 @@ public class ToscaOperationFacade {
}
if (parentVertexEither.isLeft()) {
GraphVertex previousVersionV = parentVertexEither.left().value();
- JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
+ JanusGraphOperationStatus createEdge = janusGraphDao
+ .createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
if (createEdge != JanusGraphOperationStatus.OK) {
- log.debug("Failed to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
+ log.debug("Failed to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(),
+ newVersionEither.right().value(), createEdge);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge));
}
}
@@ -711,20 +669,16 @@ public class ToscaOperationFacade {
toscaArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
}
newComponent.setToscaArtifacts(toscaArtifacts);
-
Map<String, ArtifactDefinition> artifacts = oldComponent.getArtifacts();
if (artifacts != null && !artifacts.isEmpty()) {
artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
}
newComponent.setArtifacts(artifacts);
-
Map<String, ArtifactDefinition> depArtifacts = oldComponent.getDeploymentArtifacts();
if (depArtifacts != null && !depArtifacts.isEmpty()) {
depArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
}
newComponent.setDeploymentArtifacts(depArtifacts);
-
-
newComponent.setLastUpdateDate(null);
newComponent.setHighestVersion(true);
}
@@ -735,15 +689,13 @@ public class ToscaOperationFacade {
public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
String componentId = componentToUpdate.getUniqueId();
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
}
GraphVertex elementV = getVertexEither.left().value();
ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
-
ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
Either<ToscaElement, StorageOperationStatus> updateToscaElement = null;
if (toscaElementOperation != null) {
@@ -752,30 +704,26 @@ public class ToscaOperationFacade {
log.debug("Null value returned by `getToscaElementOperation` with value {}", elementV);
updateToscaElement = Either.right(StorageOperationStatus.GENERAL_ERROR);
}
-
- return updateToscaElement.bimap(
- ModelConverter::convertFromToscaElement,
- status -> {
- log.debug("Failed to update tosca element {} error {}", componentId, status);
- return status;
- });
+ return updateToscaElement.bimap(ModelConverter::convertFromToscaElement, status -> {
+ log.debug("Failed to update tosca element {} error {}", componentId, status);
+ return status;
+ });
}
- private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
+ private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName,
+ JsonParseFlagEnum parseFlag) {
return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
}
+ // endregion
- private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
+ private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName,
+ JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
Either<T, StorageOperationStatus> result;
-
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
propertiesToMatch.put(property, nodeName);
propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
if (highestResources.isRight()) {
@@ -784,7 +732,6 @@ public class ToscaOperationFacade {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
return result;
}
-
List<GraphVertex> resources = highestResources.left().value();
double version = 0.0;
GraphVertex highestResource = null;
@@ -799,27 +746,23 @@ public class ToscaOperationFacade {
return getToscaElementByOperation(highestResource, filter);
}
- // endregion
// region - Component Get By ..
private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata);
}
public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
-
Either<List<T>, StorageOperationStatus> result = null;
Either<T, StorageOperationStatus> getComponentRes;
List<T> components = new ArrayList<>();
List<GraphVertex> componentVertices;
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
- if (componentType != null)
+ if (componentType != null) {
propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
-
+ }
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
Either<List<GraphVertex>, JanusGraphOperationStatus> getComponentsRes = janusGraphDao
.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
if (getComponentsRes.isRight()) {
@@ -832,7 +775,8 @@ public class ToscaOperationFacade {
for (GraphVertex componentVertex : componentVertices) {
getComponentRes = getToscaElementByOperation(componentVertex);
if (getComponentRes.isRight()) {
- log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
+ log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME),
+ getComponentRes.right().value());
result = Either.right(getComponentRes.right().value());
break;
}
@@ -847,16 +791,16 @@ public class ToscaOperationFacade {
return result;
}
- public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
+ public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name,
+ String version) {
return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
}
- public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
+ public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name,
+ String version, JsonParseFlagEnum parseFlag) {
Either<T, StorageOperationStatus> result;
-
Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
-
hasProperties.put(GraphPropertyEnum.NAME, name);
hasProperties.put(GraphPropertyEnum.VERSION, version);
hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
@@ -873,21 +817,18 @@ public class ToscaOperationFacade {
}
return getToscaElementByOperation(getResourceRes.left().value().get(0));
}
-
- public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVendorRelease(
- final ComponentTypeEnum componentType, final String name, final String vendorRelease,
- final JsonParseFlagEnum parseFlag) {
+ public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVendorRelease(final ComponentTypeEnum componentType,
+ final String name, final String vendorRelease,
+ final JsonParseFlagEnum parseFlag) {
Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
-
hasProperties.put(GraphPropertyEnum.NAME, name);
hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
if (componentType != null) {
hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
}
- Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
-
+ Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
.getByCriteria(null, hasProperties, hasNotProperties, predicateCriteria, parseFlag);
if (getResourceRes.isRight()) {
@@ -898,20 +839,24 @@ public class ToscaOperationFacade {
return getToscaElementByOperation(getResourceRes.left().value().get(0));
}
- public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog, List<OriginTypeEnum> excludeTypes) {
- List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
- .collect(Collectors.toList());
+ public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog,
+ List<OriginTypeEnum> excludeTypes) {
+ List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream()
+ .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
+ .collect(Collectors.toList());
return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes);
}
// endregion
- public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
+ public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType,
+ List<OriginTypeEnum> excludeTypes,
+ boolean isHighestVersions) {
List<T> components = new ArrayList<>();
Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
List<ToscaElement> toscaElements = new ArrayList<>();
- List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
- .collect(Collectors.toList());
-
+ List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream()
+ .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
+ .collect(Collectors.toList());
switch (componentType) {
case RESOURCE:
catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
@@ -963,12 +908,11 @@ public class ToscaOperationFacade {
}
private List<String> checkIfInUseAndDelete(List<GraphVertex> allMarked) {
- final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
+ final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays
+ .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
List<String> deleted = new ArrayList<>();
-
for (GraphVertex elementV : allMarked) {
boolean isAllowedToDelete = true;
-
for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
Either<Edge, JanusGraphOperationStatus> belongingEdgeByCriteria = janusGraphDao
.getBelongingEdgeByCriteria(elementV, edgeLabelEnum, null);
@@ -978,11 +922,11 @@ public class ToscaOperationFacade {
break;
}
}
-
if (isAllowedToDelete) {
Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
if (deleteToscaElement.isRight()) {
- log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(), elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
+ log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(),
+ elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
continue;
}
deleted.add(elementV.getUniqueId());
@@ -1012,8 +956,10 @@ public class ToscaOperationFacade {
}
// region - Component Update
- public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
-
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent,
+ Component origComponent,
+ ComponentInstance componentInstance,
+ boolean allowDeleted, User user) {
Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
if (StringUtils.isEmpty(componentInstance.getIcon())) {
@@ -1027,36 +973,41 @@ public class ToscaOperationFacade {
case ServiceSubstitution:
nameToFindForCounter = ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName());
break;
- default:
- nameToFindForCounter = origComponent.getName();
+ default:
+ nameToFindForCounter = origComponent.getName();
}
String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
- Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation
+ .addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
-
if (addResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ",
+ componentInstance.getName(), containerComponent.getName());
result = Either.right(addResult.right().value());
}
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
if (updateContainerComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ",
+ containerComponent.getName(), componentInstance.getName());
result = Either.right(updateContainerComponentRes.right().value());
}
}
if (result == null) {
Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
String createdInstanceId = addResult.left().value().getRight();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId,
+ updatedComponent.getName());
result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
}
return result;
}
- public void associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted, boolean isUpdateCsar) {
+ public void associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap,
+ boolean allowDeleted, boolean isUpdateCsar) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
-
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
if (metadataVertex.isRight()) {
@@ -1066,29 +1017,34 @@ public class ToscaOperationFacade {
}
throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
- Map<String, ComponentInstanceDataDefinition> compnentInstancesMap = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted, isUpdateCsar);
-
+ Map<String, ComponentInstanceDataDefinition> compnentInstancesMap = nodeTemplateOperation
+ .associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted,
+ isUpdateCsar);
containerComponent.setComponentInstances(ModelConverter.getComponentInstancesFromMapObject(compnentInstancesMap, containerComponent));
-
}
- public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
-
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(
+ Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE,
+ "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
+ containerComponent.getName());
componentInstance.setIcon(origComponent.getIcon());
- Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation
+ .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
ModelConverter.convertToToscaElement(origComponent), componentInstance);
if (updateResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
+ containerComponent.getName());
result = Either.right(updateResult.right().value());
}
if (result == null) {
Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
String createdInstanceId = updateResult.left().value().getRight();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ",
+ createdInstanceId, updatedComponent.getName());
result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
}
return result;
@@ -1098,41 +1054,45 @@ public class ToscaOperationFacade {
return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
}
- public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) {
-
+ public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent,
+ ComponentParametersView filter) {
Either<Component, StorageOperationStatus> result = null;
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
-
- Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ",
+ containerComponent.getName());
+ Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation
+ .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
if (updateResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ",
+ containerComponent.getName());
result = Either.right(updateResult.right().value());
}
if (result == null) {
Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
result = Either.left(updatedComponent);
}
return result;
}
- // endregion
-
- public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
+ // endregion
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent,
+ String resourceInstanceId) {
Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
-
- Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ",
+ resourceInstanceId, containerComponent.getName());
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation
+ .deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
if (updateResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ",
+ resourceInstanceId, containerComponent.getName());
result = Either.right(updateResult.right().value());
}
if (result == null) {
Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
String deletedInstanceId = updateResult.left().value().getRight();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ",
+ deletedInstanceId, updatedComponent.getName());
result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
}
return result;
@@ -1155,13 +1115,11 @@ public class ToscaOperationFacade {
*/
private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) {
List<String> countersInNames = containerComponent.getComponentInstances().stream()
- .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
- .map(ci -> ci.getNormalizedName().split(normalizedName)[1])
- .collect(Collectors.toList());
+ .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
+ .map(ci -> ci.getNormalizedName().split(normalizedName)[1]).collect(Collectors.toList());
List<String> countersInIds = containerComponent.getComponentInstances().stream()
- .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName))
- .map(ci -> ci.getUniqueId().split(normalizedName)[1])
- .collect(Collectors.toList());
+ .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
+ .collect(Collectors.toList());
List<String> namesAndIdsList = new ArrayList<>(countersInNames);
namesAndIdsList.addAll(countersInIds);
return getMaxInteger(namesAndIdsList);
@@ -1183,55 +1141,43 @@ public class ToscaOperationFacade {
return currCounter == null ? null : maxCounter;
}
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId, RequirementCapabilityRelDef requirementDef) {
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId,
+ RequirementCapabilityRelDef requirementDef) {
return nodeTemplateOperation.associateResourceInstances(component, componentId, requirementDef);
-
}
public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
}
-
GraphVertex vertex = getVertexEither.left().value();
- Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
-
+ Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
-
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
List<InputDefinition> inputsResList = null;
if (inputsMap != null && !inputsMap.isEmpty()) {
- inputsResList = inputsMap.values().stream()
- .map(InputDefinition::new)
- .collect(Collectors.toList());
+ inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
}
return Either.left(inputsResList);
}
return Either.right(status);
-
}
public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
}
-
GraphVertex vertex = getVertexEither.left().value();
- Map<String, PropertyDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue())));
-
- StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
-
+ Map<String, PropertyDefinition> inputsMap = inputs.entrySet().stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue())));
+ StorageOperationStatus status = topologyTemplateOperation
+ .addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
List<InputDefinition> inputsResList = null;
@@ -1241,27 +1187,19 @@ public class ToscaOperationFacade {
return Either.left(inputsResList);
}
return Either.right(status);
-
}
- public Either<List<OutputDefinition>, StorageOperationStatus> addOutputsToComponent(Map<String, OutputDefinition> outputs,
- String componentId) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ public Either<List<OutputDefinition>, StorageOperationStatus> addOutputsToComponent(Map<String, OutputDefinition> outputs, String componentId) {
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
}
-
GraphVertex vertex = getVertexEither.left().value();
Map<String, AttributeDefinition> outputsMap = outputs.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> new AttributeDefinition(e.getValue())));
-
StorageOperationStatus status = topologyTemplateOperation
.addToscaDataToToscaElement(vertex, EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputsMap, JsonPresentationFields.NAME);
-
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
List<OutputDefinition> outputsResList = null;
@@ -1271,7 +1209,6 @@ public class ToscaOperationFacade {
return Either.left(outputsResList);
}
return Either.right(status);
-
}
/**
@@ -1283,9 +1220,7 @@ public class ToscaOperationFacade {
*/
public Either<List<DataTypeDefinition>, StorageOperationStatus> addDataTypesToComponent(Map<String, DataTypeDefinition> dataTypes,
String componentId) {
-
log.trace("#addDataTypesToComponent - enter, componentId={}", componentId);
-
/* get component vertex */
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
.getVertexById(componentId, JsonParseFlagEnum.NoParse);
@@ -1296,16 +1231,14 @@ public class ToscaOperationFacade {
}
GraphVertex vertex = getVertexEither.left().value();
log.trace("#addDataTypesToComponent - get vertex ok");
-
// convert DataTypeDefinition to DataTypeDataDefinition
Map<String, DataTypeDataDefinition> dataTypeDataMap = dataTypes.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue())));
-
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue())));
// add datatype(s) to the Component.
- // if child vertex does not exist, it will be created.
- StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex,
- EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME);
+ // if child vertex does not exist, it will be created.
+ StorageOperationStatus status = topologyTemplateOperation
+ .addToscaDataToToscaElement(vertex, EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME);
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
List<DataTypeDefinition> inputsResList = null;
@@ -1314,7 +1247,6 @@ public class ToscaOperationFacade {
}
return Either.left(inputsResList);
}
-
log.trace("#addDataTypesToComponent - leave");
return Either.right(status);
}
@@ -1322,72 +1254,53 @@ public class ToscaOperationFacade {
private DataTypeDataDefinition convertDataTypeToDataTypeData(DataTypeDefinition dataType) {
DataTypeDataDefinition dataTypeData = new DataTypeDataDefinition(dataType);
if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
- List<PropertyDataDefinition> propertyDataList = dataType.getProperties().stream()
- .map(PropertyDataDefinition::new).collect(Collectors.toList());
+ List<PropertyDataDefinition> propertyDataList = dataType.getProperties().stream().map(PropertyDataDefinition::new)
+ .collect(Collectors.toList());
dataTypeData.setPropertiesData(propertyDataList);
}
-
// if "derivedFrom" data_type exists, copy the name to "derivedFromName"
if (dataType.getDerivedFrom() != null && StringUtils.isNotEmpty(dataType.getDerivedFrom().getName())) {
// if names are different, log it
if (!StringUtils.equals(dataTypeData.getDerivedFromName(), dataType.getDerivedFrom().getName())) {
- log.debug("#convertDataTypeToDataTypeData - derivedFromName(={}) overwritten by derivedFrom.name(={})",
- dataType.getDerivedFromName(), dataType.getDerivedFrom().getName());
+ log.debug("#convertDataTypeToDataTypeData - derivedFromName(={}) overwritten by derivedFrom.name(={})", dataType.getDerivedFromName(),
+ dataType.getDerivedFrom().getName());
}
dataTypeData.setDerivedFromName(dataType.getDerivedFrom().getName());
}
-
// supply "name" field to toscaPresentationValue in each datatype object for DAO operations
dataTypeData.setToscaPresentationValue(JsonPresentationFields.NAME, dataType.getName());
return dataTypeData;
}
-
public Either<List<InputDefinition>, StorageOperationStatus> getComponentInputs(String componentId) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
- if (getVertexEither.isRight()) {
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
- return Either
- .right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
}
+ Either<ToscaElement, StorageOperationStatus> toscaElement = topologyTemplateOperation.getToscaElement(componentId);
+ if (toscaElement.isRight()) {
+ return Either.right(toscaElement.right().value());
+ }
+ TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value();
+ Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();
+ List<InputDefinition> inputs = new ArrayList<>();
+ if (MapUtils.isNotEmpty(inputsMap)) {
+ inputs = inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList());
+ }
+ return Either.left(inputs);
+ }
- Either<ToscaElement, StorageOperationStatus> toscaElement =
- topologyTemplateOperation.getToscaElement(componentId);
- if(toscaElement.isRight()) {
- return Either.right(toscaElement.right().value());
- }
-
- TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value();
-
- Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();
-
- List<InputDefinition> inputs = new ArrayList<>();
- if(MapUtils.isNotEmpty(inputsMap)) {
- inputs =
- inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList());
- }
-
- return Either.left(inputs);
- }
-
- public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
}
-
GraphVertex vertex = getVertexEither.left().value();
List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
-
- StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
-
+ StorageOperationStatus status = topologyTemplateOperation
+ .updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
List<InputDefinition> inputsResList = null;
@@ -1397,48 +1310,40 @@ public class ToscaOperationFacade {
return Either.left(inputsResList);
}
return Either.right(status);
-
}
// region - ComponentInstance
- public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(
+ Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
}
-
GraphVertex vertex = getVertexEither.left().value();
Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
if (instProperties != null) {
-
MapPropertiesDataDefinition propertiesMap;
for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
propertiesMap = new MapPropertiesDataDefinition();
-
- propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
-
+ propertiesMap.setMapToscaDataDefinition(
+ entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
instPropsMap.put(entry.getKey(), propertiesMap);
}
}
-
StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
-
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
return Either.left(instProperties);
}
return Either.right(status);
-
}
/**
* saves the instInputs as the updated instance inputs of the component container in DB
*/
- public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
+ public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(
+ Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
if (instInputs == null || instInputs.isEmpty()) {
return Either.left(instInputs);
}
@@ -1447,20 +1352,23 @@ public class ToscaOperationFacade {
List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
List<String> pathKeysPerInst = new ArrayList<>();
pathKeysPerInst.add(inputsPerIntance.getKey());
- status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
+ status = topologyTemplateOperation
+ .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst,
+ pathKeysPerInst, JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
- log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
+ log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}",
+ inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
return Either.right(status);
}
}
-
return Either.left(instInputs);
}
/**
* saves the instProps as the updated instance properties of the component container in DB
*/
- public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
+ public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(
+ Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
if (instProps == null || instProps.isEmpty()) {
return Either.left(instProps);
}
@@ -1469,50 +1377,46 @@ public class ToscaOperationFacade {
List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
List<String> pathKeysPerInst = new ArrayList<>();
pathKeysPerInst.add(propsPerIntance.getKey());
- status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
+ status = topologyTemplateOperation
+ .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES,
+ toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
- log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
+ log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}",
+ propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
return Either.right(status);
}
}
-
return Either.left(instProps);
}
- public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(
+ Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
}
GraphVertex vertex = getVertexEither.left().value();
Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
if (instInputs != null) {
-
MapPropertiesDataDefinition propertiesMap;
for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
propertiesMap = new MapPropertiesDataDefinition();
-
- propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
-
+ propertiesMap.setMapToscaDataDefinition(
+ entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
instPropsMap.put(entry.getKey(), propertiesMap);
}
}
-
StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
-
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
return Either.left(instInputs);
}
return Either.right(status);
-
}
- public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
+ public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(
+ Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
requireNonNull(instProperties);
StorageOperationStatus status;
for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
@@ -1522,8 +1426,7 @@ public class ToscaOperationFacade {
for (ComponentInstanceInput property : props) {
List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId);
Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream()
- .filter(p -> p.getName().equals(property.getName()))
- .findAny();
+ .filter(p -> p.getName().equals(property.getName())).findAny();
if (instanceProperty.isPresent()) {
status = updateComponentInstanceInput(containerComponent, componentInstanceId, property);
} else {
@@ -1550,8 +1453,8 @@ public class ToscaOperationFacade {
final String componentInstanceId = entry.getKey();
if (!isEmpty(props)) {
for (final ComponentInstanceOutput property : props) {
- final List<ComponentInstanceOutput> componentInstancesInputs
- = containerComponent.getComponentInstancesOutputs().get(componentInstanceId);
+ final List<ComponentInstanceOutput> componentInstancesInputs = containerComponent.getComponentInstancesOutputs()
+ .get(componentInstanceId);
final Optional<ComponentInstanceOutput> instanceProperty = componentInstancesInputs.stream()
.filter(p -> p.getName().equals(property.getName())).findAny();
if (instanceProperty.isPresent()) {
@@ -1577,25 +1480,22 @@ public class ToscaOperationFacade {
for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
List<ComponentInstanceProperty> props = entry.getValue();
String componentInstanceId = entry.getKey();
- List<ComponentInstanceProperty> originalComponentInstProps =
- containerComponent.getComponentInstancesProperties().get(componentInstanceId);
+ List<ComponentInstanceProperty> originalComponentInstProps = containerComponent.getComponentInstancesProperties()
+ .get(componentInstanceId);
Map<String, List<CapabilityDefinition>> containerComponentCapabilities = containerComponent.getCapabilities();
-
if (isEmpty(props)) {
continue;
}
for (ComponentInstanceProperty property : props) {
StorageOperationStatus status = null;
String propertyParentUniqueId = property.getParentUniqueId();
- Optional<CapabilityDefinition>
- capPropDefinition = getPropertyCapability(propertyParentUniqueId, containerComponent);
+ Optional<CapabilityDefinition> capPropDefinition = getPropertyCapability(propertyParentUniqueId, containerComponent);
if (capPropDefinition.isPresent() && MapUtils.isNotEmpty(containerComponentCapabilities)) {
- status = populateAndUpdateInstanceCapProperty(containerComponent, componentInstanceId,
- containerComponentCapabilities, property, capPropDefinition.get());
+ status = populateAndUpdateInstanceCapProperty(containerComponent, componentInstanceId, containerComponentCapabilities, property,
+ capPropDefinition.get());
}
if (status == null) {
- status = updateOrAddComponentInstanceProperty(containerComponent, componentInstanceId,
- originalComponentInstProps, property);
+ status = updateOrAddComponentInstanceProperty(containerComponent, componentInstanceId, originalComponentInstProps, property);
}
if (status != StorageOperationStatus.OK) {
return Either.right(status);
@@ -1614,12 +1514,11 @@ public class ToscaOperationFacade {
continue;
}
final String componentInstanceId = entry.getKey();
- final List<ComponentInstanceAttribute> originalComponentInstProps =
- containerComponent.getComponentInstancesAttributes().get(componentInstanceId);
-
+ final List<ComponentInstanceAttribute> originalComponentInstProps = containerComponent.getComponentInstancesAttributes()
+ .get(componentInstanceId);
for (final ComponentInstanceAttribute property : props) {
- final StorageOperationStatus status = updateOrAddComponentInstanceAttribute(
- containerComponent, componentInstanceId, originalComponentInstProps, property);
+ final StorageOperationStatus status = updateOrAddComponentInstanceAttribute(containerComponent, componentInstanceId,
+ originalComponentInstProps, property);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
@@ -1637,32 +1536,14 @@ public class ToscaOperationFacade {
return null;
}
Optional<CapabilityDefinition> capDefToGetProp = capabilityDefinitions.stream()
- .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny();
- if(capDefToGetProp.isPresent()) {
+ .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny();
+ if (capDefToGetProp.isPresent()) {
return updateInstanceCapabilityProperty(containerComponent, componentInstanceId, property, capDefToGetProp.get());
}
return null;
}
- private static Optional<CapabilityDefinition> getPropertyCapability(String propertyParentUniqueId,
- Component containerComponent) {
-
- Map<String, List<CapabilityDefinition>> componentCapabilities = containerComponent.getCapabilities();
- if(MapUtils.isEmpty(componentCapabilities)){
- return Optional.empty();
- }
- List<CapabilityDefinition> 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))
- .findAny();
- }
-
- private StorageOperationStatus updateOrAddComponentInstanceProperty(Component containerComponent,
- String componentInstanceId,
+ private StorageOperationStatus updateOrAddComponentInstanceProperty(Component containerComponent, String componentInstanceId,
List<ComponentInstanceProperty> originalComponentInstProps,
ComponentInstanceProperty property) {
StorageOperationStatus status;
@@ -1675,14 +1556,12 @@ public class ToscaOperationFacade {
status = addComponentInstanceProperty(containerComponent, componentInstanceId, property);
}
if (status != StorageOperationStatus.OK) {
- log.debug("Failed to update instance property {} for instance {} error {} ",
- property, componentInstanceId, status);
+ log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status);
}
return status;
}
- private StorageOperationStatus updateOrAddComponentInstanceAttribute(Component containerComponent,
- String componentInstanceId,
+ private StorageOperationStatus updateOrAddComponentInstanceAttribute(Component containerComponent, String componentInstanceId,
List<ComponentInstanceAttribute> originalComponentInstProps,
ComponentInstanceAttribute property) {
StorageOperationStatus status;
@@ -1695,40 +1574,36 @@ public class ToscaOperationFacade {
status = addComponentInstanceAttribute(containerComponent, componentInstanceId, property);
}
if (status != StorageOperationStatus.OK) {
- log.debug("Failed to update instance property {} for instance {} error {} ",
- property, componentInstanceId, status);
+ log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status);
}
return status;
}
- public StorageOperationStatus updateInstanceCapabilityProperty(Component containerComponent, String componentInstanceId,
- ComponentInstanceProperty property,
- CapabilityDefinition capabilityDefinition) {
+ public StorageOperationStatus updateInstanceCapabilityProperty(Component containerComponent, String componentInstanceId,
+ ComponentInstanceProperty property, CapabilityDefinition capabilityDefinition) {
Optional<ComponentInstance> fetchedCIOptional = containerComponent.getComponentInstanceById(componentInstanceId);
if (!fetchedCIOptional.isPresent()) {
return StorageOperationStatus.GENERAL_ERROR;
}
- Either<Component, StorageOperationStatus> getComponentRes =
- getToscaFullElement(fetchedCIOptional.get().getComponentUid());
- if(getComponentRes.isRight()) {
+ Either<Component, StorageOperationStatus> getComponentRes = getToscaFullElement(fetchedCIOptional.get().getComponentUid());
+ if (getComponentRes.isRight()) {
return StorageOperationStatus.GENERAL_ERROR;
}
Optional<Component> componentOptional = isNodeServiceProxy(getComponentRes.left().value());
String propOwner;
- if(!componentOptional.isPresent()) {
+ if (!componentOptional.isPresent()) {
propOwner = componentInstanceId;
} else {
propOwner = fetchedCIOptional.get().getSourceModelUid();
}
StorageOperationStatus status;
StringBuilder sb = new StringBuilder(componentInstanceId);
- sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM)
- .append(capabilityDefinition.getType()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName());
+ sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getType())
+ .append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName());
String capKey = sb.toString();
status = updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceId, capKey, property);
if (status != StorageOperationStatus.OK) {
- log.debug("Failed to update instance capability property {} for instance {} error {} ", property,
- componentInstanceId, status);
+ log.debug("Failed to update instance capability property {} for instance {} error {} ", property, componentInstanceId, status);
return status;
}
return StorageOperationStatus.OK;
@@ -1740,78 +1615,64 @@ public class ToscaOperationFacade {
}
Resource resource = (Resource) component;
ResourceTypeEnum resType = resource.getResourceType();
- if(resType.equals(ResourceTypeEnum.ServiceProxy)) {
+ if (resType.equals(ResourceTypeEnum.ServiceProxy)) {
return Optional.of(component);
}
return Optional.empty();
}
- public StorageOperationStatus associateCapabilitiesToService(Map<String,ListCapabilityDataDefinition> capabilities, String componentId) {
-
+ public StorageOperationStatus associateCapabilitiesToService(Map<String, ListCapabilityDataDefinition> capabilities, String componentId) {
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
-
}
-
GraphVertex vertex = getVertexEither.left().value();
- if(MapUtils.isNotEmpty(capabilities)) {
- Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation.
- associateElementToData(vertex, VertexTypeEnum.CAPABILITIES,
- EdgeLabelEnum.CAPABILITIES, capabilities);
+ if (MapUtils.isNotEmpty(capabilities)) {
+ Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation
+ .associateElementToData(vertex, VertexTypeEnum.CAPABILITIES, EdgeLabelEnum.CAPABILITIES, capabilities);
if (associateElementToData.isRight()) {
return associateElementToData.right().value();
}
}
-
-
return StorageOperationStatus.OK;
-
}
public StorageOperationStatus associateRequirementsToService(Map<String, ListRequirementDataDefinition> requirements, String componentId) {
-
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
-
}
-
GraphVertex vertex = getVertexEither.left().value();
- if(MapUtils.isNotEmpty(requirements)) {
- Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation.
- associateElementToData(vertex, VertexTypeEnum.REQUIREMENTS,
- EdgeLabelEnum.REQUIREMENTS, requirements);
+ if (MapUtils.isNotEmpty(requirements)) {
+ Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation
+ .associateElementToData(vertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirements);
if (associateElementToData.isRight()) {
return associateElementToData.right().value();
}
}
-
return StorageOperationStatus.OK;
-
}
-
- public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, Component component, User user) {
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
+ Component component, User user) {
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
+ .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
-
}
-
GraphVertex vertex = getVertexEither.left().value();
Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
if (instDeploymentArtifacts != null) {
-
MapArtifactDataDefinition artifactsMap;
for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
Map<String, ArtifactDefinition> artList = entry.getValue();
- Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
- artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
-
+ Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ artifactsMap = nodeTemplateOperation
+ .prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
instArtMap.put(entry.getKey(), artifactsMap);
}
}
@@ -1820,117 +1681,108 @@ public class ToscaOperationFacade {
}
public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, Component component) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
+ .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
-
}
-
GraphVertex vertex = getVertexEither.left().value();
Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
if (instArtifacts != null) {
-
MapArtifactDataDefinition artifactsMap;
for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
Map<String, ArtifactDefinition> artList = entry.getValue();
- Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
artifactsMap = new MapArtifactDataDefinition(artifacts);
-
instArtMap.put(entry.getKey(), artifactsMap);
}
}
ModelConverter.setComponentInstancesInformationalArtifactsToComponent(instArtMap, component);
return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
-
}
- public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<AttributeDefinition>> instArttributes, Component component) {
-
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<AttributeDefinition>> instArttributes,
+ Component component) {
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
+ .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
-
}
-
GraphVertex vertex = getVertexEither.left().value();
Map<String, MapAttributesDataDefinition> instAttr = new HashMap<>();
if (instArttributes != null) {
-
MapAttributesDataDefinition attributesMap;
for (Entry<String, List<AttributeDefinition>> entry : instArttributes.entrySet()) {
final List<AttributeDefinition> value = entry.getValue();
attributesMap = new MapAttributesDataDefinition();
- attributesMap.setMapToscaDataDefinition(value.stream().map(AttributeDefinition::new)
- .collect(Collectors.toMap(AttributeDefinition::getName, e -> e)));
+ attributesMap.setMapToscaDataDefinition(
+ value.stream().map(AttributeDefinition::new).collect(Collectors.toMap(AttributeDefinition::getName, e -> e)));
instAttr.put(entry.getKey(), attributesMap);
}
}
setComponentInstanceAttributesOnComponent(component, instAttr);
return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
}
- // endregion
+ // endregion
private void setComponentInstanceAttributesOnComponent(Component resource, Map<String, MapAttributesDataDefinition> instAttr) {
Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = resource.getComponentInstancesAttributes();
- if (componentInstancesAttributes == null)
+ if (componentInstancesAttributes == null) {
componentInstancesAttributes = new HashMap<>();
+ }
componentInstancesAttributes.putAll(ModelConverter.getComponentInstancesAttributes(instAttr));
resource.setComponentInstancesAttributes(componentInstancesAttributes);
}
- public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, Component component) {
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg,
+ Component component) {
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
+ .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
-
}
-
GraphVertex vertex = getVertexEither.left().value();
-
Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
-
Map<String, MapListCapabilityDataDefinition> calcCapabilty = new HashMap<>();
Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = new HashMap<>();
if (instCapabilties != null) {
for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
-
Map<String, List<CapabilityDefinition>> caps = entry.getValue();
Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
- mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
+ mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(
+ instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
}
-
ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
- MapListCapabilityDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
-
- MapCapabilityProperty mapCapabilityProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
-
+ MapListCapabilityDataDefinition capMap = nodeTemplateOperation
+ .prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
+ MapCapabilityProperty mapCapabilityProperty = ModelConverter
+ .convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty);
}
}
-
if (instReg != null) {
for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
-
Map<String, List<RequirementDefinition>> req = entry.getValue();
Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
- mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
+ mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(
+ instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
}
-
- MapListRequirementDataDefinition reqMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
-
+ MapListRequirementDataDefinition reqMap = nodeTemplateOperation
+ .prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
String componentInstanceId = entry.getKey().getUniqueId();
calcRequirements.put(componentInstanceId, reqMap);
}
}
-
- StorageOperationStatus storageOperationStatus = topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
+ StorageOperationStatus storageOperationStatus = topologyTemplateOperation
+ .associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
updateInstancesCapAndReqOnComponentFromDB(component);
return storageOperationStatus;
}
@@ -1951,13 +1803,13 @@ public class ToscaOperationFacade {
component.setComponentInstances(updatedComponent.getComponentInstances());
}
- private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) {
+ private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps,
+ Map<GraphPropertyEnum, Object> hasNotProps) {
List<Service> services = new ArrayList<>();
List<LifecycleStateEnum> states = new ArrayList<>();
// include props
hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
// exclude props
states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
hasNotProps.put(GraphPropertyEnum.STATE, states);
@@ -1966,7 +1818,10 @@ public class ToscaOperationFacade {
return fetchServicesByCriteria(services, hasProps, hasNotProps);
}
- private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
+ private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract,
+ ComponentTypeEnum componentTypeEnum,
+ String internalComponentType,
+ VertexTypeEnum vertexType) {
List<Service> services = null;
Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
@@ -1982,21 +1837,24 @@ public class ToscaOperationFacade {
}
// region -> Fetch non checked-out services
if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
- Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
+ Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(
+ new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
if (result.isRight()) {
log.debug("Failed to fetch services for");
return Either.right(result.right().value());
}
services = result.left().value();
- if (log.isTraceEnabled() && isEmpty(services))
+ if (log.isTraceEnabled() && isEmpty(services)) {
log.trace("No relevant services available");
+ }
}
// endregion
List<Component> nonAbstractLatestComponents = new ArrayList<>();
ComponentParametersView params = new ComponentParametersView(true);
params.setIgnoreAllVersions(false);
for (GraphVertex vertexComponent : getRes.left().value()) {
- Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
+ Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation
+ .getLightComponent(vertexComponent, componentTypeEnum, params);
if (componentRes.isRight()) {
log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
return Either.right(componentRes.right().value());
@@ -2011,8 +1869,8 @@ public class ToscaOperationFacade {
return Either.left(nonAbstractLatestComponents);
}
- public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
-
+ public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag,
+ Boolean isHighest) {
Either<ComponentMetadataData, StorageOperationStatus> result;
Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
@@ -2022,15 +1880,16 @@ public class ToscaOperationFacade {
Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
-
Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
if (getRes.isRight()) {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
} else {
- List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
- ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
- : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
+ List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata)
+ .collect(Collectors.toList());
+ ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max(
+ (c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()),
+ Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
result = Either.left(latestVersion);
}
return result;
@@ -2038,8 +1897,7 @@ public class ToscaOperationFacade {
public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
Either<ComponentMetadataData, StorageOperationStatus> result;
- Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
+ Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
if (getRes.isRight()) {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
} else {
@@ -2049,9 +1907,10 @@ public class ToscaOperationFacade {
return result;
}
- public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
- String internalComponentType, List<String> componentUids) {
-
+ public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract,
+ ComponentTypeEnum componentTypeEnum,
+ String internalComponentType,
+ List<String> componentUids) {
List<Component> components = new ArrayList<>();
if (componentUids == null) {
Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType);
@@ -2067,7 +1926,8 @@ public class ToscaOperationFacade {
componentParametersView.setIgnoreCapabilities(false);
componentParametersView.setIgnoreRequirements(false);
}
- Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
+ Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum)
+ .getLightComponent(componentUid, componentTypeEnum, componentParametersView);
if (getToscaElementRes.isRight()) {
log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
return Either.right(getToscaElementRes.right().value());
@@ -2091,9 +1951,10 @@ public class ToscaOperationFacade {
component.setNormalizedName(null);
}
- private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
-
- Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum, internalComponentType);
+ private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
+ String internalComponentType) {
+ Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum,
+ internalComponentType);
if (getToscaElementsRes.isRight()) {
return Either.right(getToscaElementsRes.right().value());
}
@@ -2102,9 +1963,7 @@ public class ToscaOperationFacade {
if (collection == null) {
componentUids = new ArrayList<>();
} else {
- componentUids = collection.stream()
- .map(Component::getUniqueId)
- .collect(Collectors.toList());
+ componentUids = collection.stream().map(Component::getUniqueId).collect(Collectors.toList());
}
return Either.left(componentUids);
}
@@ -2117,7 +1976,8 @@ public class ToscaOperationFacade {
return componentParametersView;
}
- public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
+ public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType,
+ ComponentTypeEnum componentType) {
Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
if (result.isLeft()) {
result = Either.left(!result.left().value());
@@ -2125,13 +1985,13 @@ public class ToscaOperationFacade {
return result;
}
- public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
+ public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType,
+ ComponentTypeEnum componentType) {
VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
String normalizedName = ValidationUtils.normaliseComponentName(name);
Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
-
Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
@@ -2141,12 +2001,10 @@ public class ToscaOperationFacade {
return Either.left(CollectionUtils.isEmpty(vertexEither.isLeft() ? vertexEither.left().value() : null));
}
- private void fillNodeTypePropsMap(final Map<GraphPropertyEnum, Object> hasProps,
- final Map<GraphPropertyEnum, Object> hasNotProps,
+ private void fillNodeTypePropsMap(final Map<GraphPropertyEnum, Object> hasProps, final Map<GraphPropertyEnum, Object> hasNotProps,
final String internalComponentType) {
final Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
final List<String> allowedTypes;
-
if (ComponentTypeEnum.SERVICE.getValue().equalsIgnoreCase(internalComponentType)) {
allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.SERVICE, null);
} else {
@@ -2158,17 +2016,16 @@ public class ToscaOperationFacade {
hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, allResourceTypes);
return;
}
-
if (ResourceTypeEnum.VL.getValue().equalsIgnoreCase(internalComponentType)) {
hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, allowedTypes);
} else {
- final List<String> notAllowedTypes = allResourceTypes.stream().filter(s -> !allowedTypes.contains(s))
- .collect(Collectors.toList());
+ final List<String> notAllowedTypes = allResourceTypes.stream().filter(s -> !allowedTypes.contains(s)).collect(Collectors.toList());
hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, notAllowedTypes);
}
}
- private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum) {
+ private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps,
+ ComponentTypeEnum componentTypeEnum) {
switch (componentTypeEnum) {
case RESOURCE:
hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
@@ -2182,9 +2039,9 @@ public class ToscaOperationFacade {
hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
}
- private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
+ private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType,
+ ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
-
hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
@@ -2209,21 +2066,24 @@ public class ToscaOperationFacade {
return internalVertexTypes;
}
- public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
+ public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract,
+ ComponentTypeEnum componentTypeEnum,
+ String internalComponentType) {
List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
List<Component> result = new ArrayList<>();
for (VertexTypeEnum vertexType : internalVertexTypes) {
- Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, componentTypeEnum, internalComponentType, vertexType);
+ Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract,
+ componentTypeEnum, internalComponentType, vertexType);
if (listByVertexType.isRight()) {
return listByVertexType;
}
result.addAll(listByVertexType.left().value());
}
return Either.left(result);
-
}
- private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
+ private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid,
+ Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
if (additionalPropertiesToMatch != null) {
propertiesToMatch.putAll(additionalPropertiesToMatch);
@@ -2234,10 +2094,8 @@ public class ToscaOperationFacade {
public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
-
Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
@@ -2245,55 +2103,43 @@ public class ToscaOperationFacade {
if (vertexEither.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
}
-
List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
return Either.right(StorageOperationStatus.NOT_FOUND);
}
-
return getToscaElementByOperation(vertexList.get(0));
}
- public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
-
+ public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid,
+ Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
if (additionalPropertiesToMatch != null) {
propertiesToMatch.putAll(additionalPropertiesToMatch);
}
-
propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
-
Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
-
Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
-
if (vertexEither.isRight()) {
log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
}
List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
-
if (vertexList == null || vertexList.isEmpty()) {
log.debug("Component with uuid {} was not found", componentUuid);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
-
ArrayList<Component> latestComponents = new ArrayList<>();
for (GraphVertex vertex : vertexList) {
Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
-
if (toscaElementByOperation.isRight()) {
log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
return Either.right(toscaElementByOperation.right().value());
}
-
latestComponents.add(toscaElementByOperation.left().value());
}
-
if (latestComponents.size() > 1) {
for (Component component : latestComponents) {
if (Boolean.TRUE.equals(component.isHighestVersion())) {
@@ -2303,7 +2149,6 @@ public class ToscaOperationFacade {
}
}
}
-
return Either.left(latestComponents);
}
@@ -2317,30 +2162,26 @@ public class ToscaOperationFacade {
return getLatestComponentByUuid(componentUuid, null);
}
- public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {
-
+ public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid,
+ Map<GraphPropertyEnum, Object> propertiesToMatch) {
Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
-
if (latestVersionListEither.isRight()) {
return Either.right(latestVersionListEither.right().value());
}
-
List<Component> latestVersionList = latestVersionListEither.left().value();
-
if (latestVersionList.isEmpty()) {
return Either.right(StorageOperationStatus.NOT_FOUND);
}
- Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
-
+ Component component = latestVersionList.size() == 1 ? latestVersionList.get(0)
+ : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion())))
+ .get();
return Either.left(component);
}
public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
-
List<Resource> resources = new ArrayList<>();
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
if (isHighest != null) {
propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
@@ -2348,10 +2189,8 @@ public class ToscaOperationFacade {
propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
Either<List<GraphVertex>, JanusGraphOperationStatus> getResourcesRes = janusGraphDao
.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
-
if (getResourcesRes.isRight()) {
log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResourcesRes.right().value()));
@@ -2367,18 +2206,15 @@ public class ToscaOperationFacade {
return Either.left(resources);
}
- public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version,
+ JsonParseFlagEnum parseFlag) {
Either<T, StorageOperationStatus> result;
-
Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
-
hasProperties.put(GraphPropertyEnum.NAME, name);
hasProperties.put(GraphPropertyEnum.VERSION, version);
hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
-
Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
if (getResourceRes.isRight()) {
@@ -2390,11 +2226,13 @@ public class ToscaOperationFacade {
return getToscaElementByOperation(getResourceRes.left().value().get(0));
}
- public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
+ public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID,
+ String systemName) {
return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll);
}
- public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, JsonParseFlagEnum parseFlag) {
+ public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID,
+ String systemName, JsonParseFlagEnum parseFlag) {
Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
@@ -2403,7 +2241,6 @@ public class ToscaOperationFacade {
props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
}
propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
-
GraphVertex resourceMetadataData = null;
List<GraphVertex> resourceMetadataDataList = null;
Either<List<GraphVertex>, JanusGraphOperationStatus> byCsar = janusGraphDao
@@ -2412,21 +2249,22 @@ public class ToscaOperationFacade {
if (JanusGraphOperationStatus.NOT_FOUND == byCsar.right().value()) {
// Fix Defect DE256036
if (StringUtils.isEmpty(systemName)) {
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- JanusGraphOperationStatus.NOT_FOUND));
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.NOT_FOUND));
}
-
props.clear();
props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
Either<List<GraphVertex>, JanusGraphOperationStatus> bySystemname = janusGraphDao
.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
if (bySystemname.isRight()) {
- log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
+ log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName,
+ bySystemname.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(bySystemname.right().value()));
}
if (bySystemname.left().value().size() > 2) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
+ log.debug(
+ "getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}",
+ bySystemname.left().value().size());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
resourceMetadataDataList = bySystemname.left().value();
@@ -2444,9 +2282,12 @@ public class ToscaOperationFacade {
log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
- if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
- log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
+ if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData
+ .getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
+ log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName,
+ resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
// correct error will be returned from create flow. with all
+
// correct audit records!!!!!
return Either.right(StorageOperationStatus.NOT_FOUND);
}
@@ -2455,7 +2296,8 @@ public class ToscaOperationFacade {
} else {
resourceMetadataDataList = byCsar.left().value();
if (resourceMetadataDataList.size() > 2) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}",
+ byCsar.left().value().size());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
if (resourceMetadataDataList.size() == 1) {
@@ -2478,26 +2320,22 @@ public class ToscaOperationFacade {
}
public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
-
String currentTemplateNameChecked = templateNameExtends;
-
while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
-
if (latestByToscaResourceName.isRight()) {
- return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
+ return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false)
+ : Either.right(latestByToscaResourceName.right().value());
}
-
Resource value = latestByToscaResourceName.left().value();
-
if (value.getDerivedFrom() != null) {
currentTemplateNameChecked = value.getDerivedFrom().get(0);
} else {
currentTemplateNameChecked = null;
}
}
-
- return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
+ return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true)
+ : Either.left(false);
}
public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
@@ -2508,18 +2346,14 @@ public class ToscaOperationFacade {
propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> resourcesByTypeEither = janusGraphDao
.getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
-
if (resourcesByTypeEither.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resourcesByTypeEither.right().value()));
}
-
List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
List<Component> components = new ArrayList<>();
-
for (GraphVertex vertex : vertexList) {
components.add(getToscaElementByOperation(vertex, filterBy).left().value());
}
-
return Either.left(components);
}
@@ -2528,7 +2362,8 @@ public class ToscaOperationFacade {
}
public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
- Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
+ Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation
+ .updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
if (updateDistributionStatus.isRight()) {
return Either.right(updateDistributionStatus.right().value());
}
@@ -2539,12 +2374,10 @@ public class ToscaOperationFacade {
}
public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component) {
-
Either<ComponentMetadataData, StorageOperationStatus> result = null;
GraphVertex serviceVertex;
Either<GraphVertex, JanusGraphOperationStatus> updateRes = null;
- Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao
- .getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+ Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
if (getRes.isRight()) {
JanusGraphOperationStatus status = getRes.right().value();
log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
@@ -2573,29 +2406,24 @@ public class ToscaOperationFacade {
public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
-
return getServicesWithDistStatus(distStatus, propertiesToMatch);
}
- public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
-
+ public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus,
+ Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
List<Service> servicesAll = new ArrayList<>();
-
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
propertiesToMatch.putAll(additionalPropertiesToMatch);
}
-
propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
-
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
if (distStatus != null && !distStatus.isEmpty()) {
for (DistributionStatusEnum state : distStatus) {
propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
- Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
+ Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch,
+ propertiesNotToMatch);
if (fetchServicesByCriteria.isRight()) {
return fetchServicesByCriteria;
} else {
@@ -2608,20 +2436,25 @@ public class ToscaOperationFacade {
}
}
- private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
+ private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll,
+ Map<GraphPropertyEnum, Object> propertiesToMatch,
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
if (getRes.isRight()) {
if (getRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+ "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch,
+ propertiesNotToMatch, getRes.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
}
} else {
for (GraphVertex vertex : getRes.left().value()) {
- Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
-
+ Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation
+ .getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
if (getServiceRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ",
+ vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
return Either.right(getServiceRes.right().value());
} else {
servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
@@ -2635,16 +2468,19 @@ public class ToscaOperationFacade {
janusGraphDao.rollback();
}
- public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
- Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
-
+ public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance,
+ Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
+ Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
}
- public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
+ public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance,
+ Map<String, ArtifactDefinition> artifacts) {
StorageOperationStatus status = StorageOperationStatus.OK;
if (MapUtils.isNotEmpty(artifacts)) {
- Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
}
return status;
@@ -2658,141 +2494,146 @@ public class ToscaOperationFacade {
return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
}
- public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(String propertyName,
- PropertyDefinition newPropertyDefinition,
- Component component) {
- newPropertyDefinition.setName(propertyName);
-
- StorageOperationStatus status = getToscaElementOperation(component)
- .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName, component.getName(), status);
+ public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(String propertyName, PropertyDefinition newPropertyDefinition,
+ Component component) {
+ newPropertyDefinition.setName(propertyName);
+ StorageOperationStatus status = getToscaElementOperation(component)
+ .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
+ JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName,
+ component.getName(), status);
return Either.right(status);
- }
-
+ }
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreProperties(false);
filter.setIgnoreInputs(false);
Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(),
+ getUpdatedComponentRes.right().value());
return Either.right(status);
}
-
PropertyDefinition newProperty = null;
- List<PropertyDefinition> properties =
- (getUpdatedComponentRes.left().value()).getProperties();
+ List<PropertyDefinition> properties = (getUpdatedComponentRes.left().value()).getProperties();
if (CollectionUtils.isNotEmpty(properties)) {
- Optional<PropertyDefinition> propertyOptional = properties.stream().filter(
- propertyEntry -> propertyEntry.getName().equals(propertyName)).findAny();
+ Optional<PropertyDefinition> propertyOptional = properties.stream().filter(propertyEntry -> propertyEntry.getName().equals(propertyName))
+ .findAny();
if (propertyOptional.isPresent()) {
newProperty = propertyOptional.get();
}
}
if (newProperty == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ", propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ",
+ propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
-
return Either.left(newProperty);
- }
+ }
- public Either<InputDefinition, StorageOperationStatus> addInputToComponent(String inputName,
- InputDefinition newInputDefinition,
- Component component) {
+ public Either<InputDefinition, StorageOperationStatus> addInputToComponent(String inputName, InputDefinition newInputDefinition,
+ Component component) {
newInputDefinition.setName(inputName);
-
StorageOperationStatus status = getToscaElementOperation(component)
- .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
+ .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
+ JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the input {} to the component {}. Status is {}. ", inputName, component.getName(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the input {} to the component {}. Status is {}. ", inputName,
+ component.getName(), status);
return Either.right(status);
}
-
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreProperties(false);
filter.setIgnoreInputs(false);
Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(),
+ getUpdatedComponentRes.right().value());
return Either.right(status);
}
-
InputDefinition newInput = null;
- List<InputDefinition> inputs =
- (getUpdatedComponentRes.left().value()).getInputs();
+ List<InputDefinition> inputs = (getUpdatedComponentRes.left().value()).getInputs();
if (CollectionUtils.isNotEmpty(inputs)) {
- Optional<InputDefinition> inputOptional = inputs.stream().filter(
- inputEntry -> inputEntry.getName().equals(inputName)).findAny();
+ Optional<InputDefinition> inputOptional = inputs.stream().filter(inputEntry -> inputEntry.getName().equals(inputName)).findAny();
if (inputOptional.isPresent()) {
newInput = inputOptional.get();
}
}
if (newInput == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added input {} " +
- "on the component {}. Status is {}. ", inputs, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added input {} " + "on the component {}. Status is {}. ", inputs,
+ component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
-
return Either.left(newInput);
}
- public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) {
- return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
- }
+ public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) {
+ return getToscaElementOperation(component)
+ .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName,
+ JsonPresentationFields.NAME);
+ }
- public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
- return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
- }
+ public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
+ return getToscaElementOperation(component)
+ .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName,
+ JsonPresentationFields.NAME);
+ }
public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
- return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
+ return getToscaElementOperation(resource)
+ .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
}
public StorageOperationStatus deleteOutputOfResource(final Component resource, final String outputName) {
- return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputName, JsonPresentationFields.NAME);
+ return getToscaElementOperation(resource)
+ .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputName, JsonPresentationFields.NAME);
}
/**
* Deletes a data type from a component.
- * @param component the container which has the data type
+ *
+ * @param component the container which has the data type
* @param dataTypeName the data type name to be deleted
* @return Operation result.
*/
public StorageOperationStatus deleteDataTypeOfComponent(Component component, String dataTypeName) {
- return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName, JsonPresentationFields.NAME);
+ return getToscaElementOperation(component)
+ .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName,
+ JsonPresentationFields.NAME);
}
- public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfComponent(Component component,
- PropertyDefinition newPropertyDefinition) {
-
- Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
- Either<PropertyDefinition, StorageOperationStatus> result = null;
- StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS,
- newPropertyDefinition.getName(), component.getName(), status);
+ public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfComponent(Component component,
+ PropertyDefinition newPropertyDefinition) {
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<PropertyDefinition, StorageOperationStatus> result = null;
+ StorageOperationStatus status = getToscaElementOperation(component)
+ .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
+ JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
+ component.getName(), status);
result = Either.right(status);
}
- if (result == null) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreProperties(false);
- getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
- if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS,
- component.getUniqueId(), getUpdatedComponentRes.right().value());
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreProperties(false);
+ getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
+ getUpdatedComponentRes.right().value());
result = Either.right(status);
}
- }
- if (result == null) {
- Optional<PropertyDefinition> newProperty = (getUpdatedComponentRes.left().value())
- .getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
+ }
+ if (result == null) {
+ Optional<PropertyDefinition> newProperty = (getUpdatedComponentRes.left().value()).getProperties().stream()
+ .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
if (newProperty.isPresent()) {
result = Either.left(newProperty.get());
} else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
- FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
- component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
+ newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
@@ -2801,15 +2642,15 @@ public class ToscaOperationFacade {
public Either<AttributeDefinition, StorageOperationStatus> updateAttributeOfComponent(Component component,
AttributeDefinition newPropertyDefinition) {
-
Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
Either<AttributeDefinition, StorageOperationStatus> result = null;
StorageOperationStatus status = getToscaElementOperation(component)
- .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES,
- newPropertyDefinition, JsonPresentationFields.NAME);
+ .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newPropertyDefinition,
+ JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS,
- newPropertyDefinition.getName(), component.getName(), status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
+ component.getName(), status);
result = Either.right(status);
}
if (result == null) {
@@ -2817,29 +2658,26 @@ public class ToscaOperationFacade {
filter.setIgnoreProperties(false);
getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS,
- component.getUniqueId(), getUpdatedComponentRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
+ getUpdatedComponentRes.right().value());
result = Either.right(status);
}
}
if (result == null) {
- Optional<AttributeDefinition> newProperty = (getUpdatedComponentRes.left().value())
- .getAttributes().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
+ Optional<AttributeDefinition> newProperty = (getUpdatedComponentRes.left().value()).getAttributes().stream()
+ .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
if (newProperty.isPresent()) {
result = Either.left(newProperty.get());
} else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
- FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
- component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
+ newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
return result;
}
- public Either<AttributeDefinition, StorageOperationStatus> addAttributeOfResource(Component component,
- AttributeDefinition newAttributeDef) {
-
+ public Either<AttributeDefinition, StorageOperationStatus> addAttributeOfResource(Component component, AttributeDefinition newAttributeDef) {
Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
Either<AttributeDefinition, StorageOperationStatus> result = null;
if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
@@ -2847,12 +2685,12 @@ public class ToscaOperationFacade {
newAttributeDef.setUniqueId(attUniqueId);
newAttributeDef.setOwnerId(component.getUniqueId());
}
-
StorageOperationStatus status = getToscaElementOperation(component)
.addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(),
+ component.getName(), status);
result = Either.right(status);
}
if (result == null) {
@@ -2860,17 +2698,19 @@ public class ToscaOperationFacade {
filter.setIgnoreAttributes(false);
getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
+ getUpdatedComponentRes.right().value());
result = Either.right(status);
}
}
if (result == null) {
- Optional<AttributeDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value())
- .getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
+ Optional<AttributeDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream()
+ .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
if (newAttribute.isPresent()) {
result = Either.left(newAttribute.get());
} else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
+ newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
@@ -2878,12 +2718,14 @@ public class ToscaOperationFacade {
}
public Either<AttributeDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, AttributeDefinition newAttributeDef) {
-
Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
Either<AttributeDefinition, StorageOperationStatus> result = null;
- StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
+ StorageOperationStatus status = getToscaElementOperation(component)
+ .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
+ JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(),
+ component.getName(), status);
result = Either.right(status);
}
if (result == null) {
@@ -2891,17 +2733,19 @@ public class ToscaOperationFacade {
filter.setIgnoreAttributes(false);
getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
+ getUpdatedComponentRes.right().value());
result = Either.right(status);
}
}
if (result == null) {
- Optional<AttributeDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value())
- .getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
+ Optional<AttributeDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream()
+ .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
if (newProperty.isPresent()) {
result = Either.left(newProperty.get());
} else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
+ newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
@@ -2909,12 +2753,14 @@ public class ToscaOperationFacade {
}
public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
-
Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
Either<InputDefinition, StorageOperationStatus> result = null;
- StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
+ StorageOperationStatus status = getToscaElementOperation(component)
+ .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
+ JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ",
+ newInputDefinition.getName(), component.getName(), status);
result = Either.right(status);
}
if (result == null) {
@@ -2922,16 +2768,19 @@ public class ToscaOperationFacade {
filter.setIgnoreInputs(false);
getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
+ getUpdatedComponentRes.right().value());
result = Either.right(status);
}
}
if (result == null) {
- Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
+ Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream()
+ .filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
if (updatedInput.isPresent()) {
result = Either.left(updatedInput.get());
} else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ",
+ newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
@@ -2946,53 +2795,67 @@ public class ToscaOperationFacade {
* @param componentInstanceId - id
* @return - successfull/failed status
**/
- public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) {
+ public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent,
+ ComponentInstance componentInstance,
+ String componentInstanceId) {
String uniqueId = componentInstance.getUniqueId();
- StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId);
+ StorageOperationStatus status = nodeTemplateOperation
+ .deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS,
+ uniqueId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
return Either.right(status);
}
if (componentInstance.getGroupInstances() != null) {
status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
+ CommonUtility
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId,
+ status);
return Either.right(status);
}
}
return Either.left(status);
}
- public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
+ List<GroupDefinition> groups,
+ Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
}
- public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
+ public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component,
+ List<GroupDataDefinition> updatedGroups) {
return groupsOperation.updateGroups(component, updatedGroups, PromoteVersionEnum.MINOR);
}
- public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) {
+ public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId,
+ List<GroupInstance> updatedGroupInstances) {
return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
}
- public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
+ List<GroupInstance> groupInstances) {
return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
}
- public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
+ public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance,
+ Map<String, ArtifactDefinition> deploymentArtifacts) {
return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
}
- public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
+ public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId,
+ ComponentInstanceProperty property) {
return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
}
- public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
+ public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId,
+ List<ComponentInstanceProperty> properties) {
return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
}
- public StorageOperationStatus updateComponentInstanceAttributes(final Component containerComponent,
- final String componentInstanceId,
+ public StorageOperationStatus updateComponentInstanceAttributes(final Component containerComponent, final String componentInstanceId,
final List<ComponentInstanceAttribute> attributes) {
return nodeTemplateOperation.updateComponentInstanceAttributes(containerComponent, componentInstanceId, attributes);
}
@@ -3002,8 +2865,7 @@ public class ToscaOperationFacade {
return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
}
- public StorageOperationStatus updateComponentInstanceAttribute(final Component containerComponent,
- final String componentInstanceId,
+ public StorageOperationStatus updateComponentInstanceAttribute(final Component containerComponent, final String componentInstanceId,
final ComponentInstanceAttribute attribute) {
return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, attribute);
}
@@ -3064,64 +2926,60 @@ public class ToscaOperationFacade {
}
public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId,
- String capabilityPropertyKey,
- ComponentInstanceProperty property) {
+ String capabilityPropertyKey, ComponentInstanceProperty property) {
return nodeTemplateOperation
.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityPropertyKey, property);
}
- public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent,
- String componentInstanceUniqueId) {
- return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
- .map(instanceCapProps -> topologyTemplateOperation
- .updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
- .orElse(StorageOperationStatus.NOT_FOUND);
+ public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
+ return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId).map(instanceCapProps -> topologyTemplateOperation
+ .updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
+ .orElse(StorageOperationStatus.NOT_FOUND);
}
-
- public StorageOperationStatus updateComponentInstanceRequirement(String containerComponentId, String componentInstanceUniqueId, RequirementDataDefinition requirementDataDefinition) {
+
+ public StorageOperationStatus updateComponentInstanceRequirement(String containerComponentId, String componentInstanceUniqueId,
+ RequirementDataDefinition requirementDataDefinition) {
return nodeTemplateOperation.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition);
}
public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceUniqueId) {
- MapInterfaceDataDefinition mapInterfaceDataDefinition =
- convertComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId);
- return topologyTemplateOperation
- .updateComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId, mapInterfaceDataDefinition);
+ MapInterfaceDataDefinition mapInterfaceDataDefinition = convertComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId);
+ return topologyTemplateOperation.updateComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId, mapInterfaceDataDefinition);
}
- public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
- Map<String, MapCapabilityProperty> mapCapabiltyPropertyMap =
- convertComponentCapabilitiesProperties(containerComponent);
- return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
- }
+ public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
+ Map<String, MapCapabilityProperty> mapCapabiltyPropertyMap = convertComponentCapabilitiesProperties(containerComponent);
+ return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
+ }
public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
- StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
+ StorageOperationStatus status = topologyTemplateOperation
+ .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
if (status == StorageOperationStatus.OK) {
- status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
+ status = topologyTemplateOperation
+ .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
}
if (status == StorageOperationStatus.OK) {
- status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
+ status = topologyTemplateOperation
+ .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
}
return status;
}
public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
String componentId = clonedResource.getUniqueId();
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
-
}
GraphVertex nodeTypeV = getVertexEither.left().value();
-
ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
-
- Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
+ Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation
+ .shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) {
- log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
+ log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0),
+ shouldUpdateDerivedVersion.right().value());
return Either.right(shouldUpdateDerivedVersion.right().value());
}
if (shouldUpdateDerivedVersion.isLeft()) {
@@ -3133,35 +2991,36 @@ public class ToscaOperationFacade {
/**
* Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
*/
- public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
+ public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId,
+ String instanceId,
+ String capabilityName,
+ String capabilityType,
+ String ownerId) {
return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
}
- private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent,
- String componentInstanceId) {
- MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
- List<ComponentInstanceInterface> componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId);
-
- if(CollectionUtils.isNotEmpty(componentInterface)) {
- componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put
- (interfaceDef.getUniqueId(), interfaceDef));
- }
-
- return mapInterfaceDataDefinition;
- }
+ private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent, String componentInstanceId) {
+ MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
+ List<ComponentInstanceInterface> componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId);
+ if (CollectionUtils.isNotEmpty(componentInterface)) {
+ componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put(interfaceDef.getUniqueId(), interfaceDef));
+ }
+ return mapInterfaceDataDefinition;
+ }
- private Map<String, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) {
- Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true);
- map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true));
- return map;
- }
+ private Map<String, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) {
+ Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true);
+ map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true));
+ return map;
+ }
private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) {
return component.fetchInstanceById(instanceId)
- .map(ci -> ModelConverter.convertToMapOfMapCapabilityProperties(ci.getCapabilities(), instanceId, ci.getOriginType().isAtomicType()));
+ .map(ci -> ModelConverter.convertToMapOfMapCapabilityProperties(ci.getCapabilities(), instanceId, ci.getOriginType().isAtomicType()));
}
- public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
+ public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition,
+ int counter) {
Either<PolicyDefinition, StorageOperationStatus> result = null;
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
@@ -3175,7 +3034,8 @@ public class ToscaOperationFacade {
}
}
if (result == null) {
- StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
+ StorageOperationStatus status = topologyTemplateOperation
+ .addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
@@ -3189,11 +3049,12 @@ public class ToscaOperationFacade {
public StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) {
log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId);
return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
- .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
+ DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
- public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition, PromoteVersionEnum promoteVersionEnum) {
+ public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition,
+ PromoteVersionEnum promoteVersionEnum) {
Either<PolicyDefinition, StorageOperationStatus> result = null;
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
@@ -3216,17 +3077,14 @@ public class ToscaOperationFacade {
public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
- return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
- .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
- err -> err);
+ return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
+ .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition), err -> err);
}
public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
StorageOperationStatus status = null;
- Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
@@ -3238,61 +3096,42 @@ public class ToscaOperationFacade {
}
public boolean canAddGroups(String componentId) {
- GraphVertex vertex = janusGraphDao.getVertexById(componentId)
- .left()
- .on(this::onJanusGraphError);
+ GraphVertex vertex = janusGraphDao.getVertexById(componentId).left().on(this::onJanusGraphError);
return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS);
}
GraphVertex onJanusGraphError(JanusGraphOperationStatus toe) {
- throw new StorageException(
- DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toe));
+ throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toe));
}
public CatalogUpdateTimestamp updateCatalogTimes() {
long now = System.currentTimeMillis();
-
- GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT)
- .left()
- .on(this::onJanusGraphError);
-
+ GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().on(this::onJanusGraphError);
Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
catalogRoot.addMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME, currentTime);
catalogRoot.addMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME, now);
-
janusGraphDao.updateVertex(catalogRoot).left().on(this::onJanusGraphError);
-
return new CatalogUpdateTimestamp(currentTime, now);
}
public CatalogUpdateTimestamp getCatalogTimes() {
-
-
- GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT)
- .left()
- .on(this::onJanusGraphError);
-
+ GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().on(this::onJanusGraphError);
Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
Long prevTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME);
-
return new CatalogUpdateTimestamp(prevTime == null ? 0 : prevTime.longValue(), currentTime == null ? 0 : currentTime.longValue());
}
public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId) {
- topologyTemplateOperation
- .updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
+ topologyTemplateOperation.updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
}
public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) {
- topologyTemplateOperation
- .revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
+ topologyTemplateOperation.revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
}
private TopologyTemplate getTopologyTemplate(String componentId) {
- return (TopologyTemplate) topologyTemplateOperation
- .getToscaElement(componentId, getFilterComponentWithCapProperties())
- .left()
- .on(this::throwStorageException);
+ return (TopologyTemplate) topologyTemplateOperation.getToscaElement(componentId, getFilterComponentWithCapProperties()).left()
+ .on(this::throwStorageException);
}
private ComponentParametersView getFilterComponentWithCapProperties() {
@@ -3306,12 +3145,13 @@ public class ToscaOperationFacade {
}
public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
- final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
+ final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays
+ .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
if (vertexById.isLeft()) {
for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
Iterator<Edge> edgeItr = vertexById.left().value().getVertex().edges(Direction.IN, edgeLabelEnum.name());
- if(edgeItr != null && edgeItr.hasNext()){
+ if (edgeItr != null && edgeItr.hasNext()) {
return Either.left(true);
}
}
@@ -3319,41 +3159,36 @@ public class ToscaOperationFacade {
return Either.left(false);
}
- public Either<List<Component>, StorageOperationStatus> getComponentListByInvariantUuid
- (String componentInvariantUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
-
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) {
- propertiesToMatch.putAll(additionalPropertiesToMatch);
- }
- propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid);
-
- Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
- .getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
-
- if (vertexEither.isRight()) {
- log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid, vertexEither.right().value());
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
- }
- List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
-
- if (vertexList == null || vertexList.isEmpty()) {
- log.debug("Component with invariantUUId {} was not found", componentInvariantUuid);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
-
- ArrayList<Component> components = new ArrayList<>();
- for (GraphVertex vertex : vertexList) {
- Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
- if (toscaElementByOperation.isRight()) {
- log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId());
- return Either.right(toscaElementByOperation.right().value());
- }
- components.add(toscaElementByOperation.left().value());
- }
-
- return Either.left(components);
- }
+ public Either<List<Component>, StorageOperationStatus> getComponentListByInvariantUuid(String componentInvariantUuid,
+ Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) {
+ propertiesToMatch.putAll(additionalPropertiesToMatch);
+ }
+ propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid);
+ Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
+ .getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
+ if (vertexEither.isRight()) {
+ log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid,
+ vertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
+ }
+ List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
+ if (vertexList == null || vertexList.isEmpty()) {
+ log.debug("Component with invariantUUId {} was not found", componentInvariantUuid);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ ArrayList<Component> components = new ArrayList<>();
+ for (GraphVertex vertex : vertexList) {
+ Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
+ if (toscaElementByOperation.isRight()) {
+ log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId());
+ return Either.right(toscaElementByOperation.right().value());
+ }
+ components.add(toscaElementByOperation.left().value());
+ }
+ return Either.left(components);
+ }
public Either<List<Component>, StorageOperationStatus> getParentComponents(String componentId) {
List<Component> parentComponents = new ArrayList<>();
@@ -3363,9 +3198,9 @@ public class ToscaOperationFacade {
for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) {
Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
.getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson);
- if(parentVertexEither.isLeft()){
+ if (parentVertexEither.isLeft()) {
Either<Component, StorageOperationStatus> componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId());
- if(componentEither.isLeft()){
+ if (componentEither.isLeft()) {
parentComponents.add(componentEither.left().value());
}
}
@@ -3373,13 +3208,12 @@ public class ToscaOperationFacade {
}
return Either.left(parentComponents);
}
+
public void updateCapReqPropertiesOwnerId(String componentId) {
- topologyTemplateOperation
- .updateCapReqPropertiesOwnerId(componentId, getTopologyTemplate(componentId));
+ topologyTemplateOperation.updateCapReqPropertiesOwnerId(componentId, getTopologyTemplate(componentId));
}
public <T extends Component> Either<T, StorageOperationStatus> getLatestByServiceName(String serviceName) {
return getLatestByName(GraphPropertyEnum.NAME, serviceName);
-
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java
index b97afb64f0..a8b793db66 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
-import org.janusgraph.core.JanusGraphVertex;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.janusgraph.core.JanusGraphVertex;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
@@ -40,12 +46,9 @@ import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Component;
-import java.util.*;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
@Component
public class UpgradeOperation extends BaseOperation {
+
private static final Logger log = Logger.getLogger(UpgradeOperation.class.getName());
public Either<List<ComponentDependency>, StorageOperationStatus> getComponentDependencies(String componentId) {
@@ -55,14 +58,11 @@ public class UpgradeOperation extends BaseOperation {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexById.right().value()));
}
List<ComponentDependency> dependencies = new ArrayList<>();
-
GraphVertex vertex = vertexById.left().value();
-
StorageOperationStatus status = fillDependenciesByVertex(componentId, dependencies, vertex);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
-
GraphVertex vertexToStart = vertex;
Function<GraphVertex, Either<GraphVertex, JanusGraphOperationStatus>> getNextElement = vertexP -> janusGraphDao
.getParentVertex(vertexP, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll);
@@ -71,15 +71,13 @@ public class UpgradeOperation extends BaseOperation {
return Either.right(status);
}
vertex = vertexToStart;
- getNextElement = vertexP -> janusGraphDao
- .getChildVertex(vertexP, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll);
+ getNextElement = vertexP -> janusGraphDao.getChildVertex(vertexP, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll);
status = handleVersionChain(componentId, dependencies, vertex, getNextElement);
-
return status == StorageOperationStatus.OK ? Either.left(dependencies) : Either.right(status);
}
- private StorageOperationStatus handleVersionChain(String componentId, List<ComponentDependency> dependencies, GraphVertex vertexToStart, Function<GraphVertex, Either<GraphVertex, JanusGraphOperationStatus>> getNextElement) {
-
+ private StorageOperationStatus handleVersionChain(String componentId, List<ComponentDependency> dependencies, GraphVertex vertexToStart,
+ Function<GraphVertex, Either<GraphVertex, JanusGraphOperationStatus>> getNextElement) {
StorageOperationStatus status;
boolean nextInChain = true;
GraphVertex vertex = vertexToStart;
@@ -101,9 +99,8 @@ public class UpgradeOperation extends BaseOperation {
private StorageOperationStatus fillDependenciesByVertex(String componentId, List<ComponentDependency> dependencies, GraphVertex vertex) {
StorageOperationStatus status = StorageOperationStatus.OK;
- if ( needToAddToDependency(vertex) ) {
+ if (needToAddToDependency(vertex)) {
ComponentDependency dependency = fillDataFromVertex(vertex, null, null);
-
List<EdgeLabelEnum> dependList = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
for (EdgeLabelEnum label : dependList) {
status = fillDependenciesByLabel(componentId, vertex, dependency, label);
@@ -119,21 +116,24 @@ public class UpgradeOperation extends BaseOperation {
return status;
}
- private boolean needToAddToDependency(GraphVertex vertex){
- Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
+ private boolean needToAddToDependency(GraphVertex vertex) {
+ Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
Boolean isArchived = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED);
return !Boolean.TRUE.equals(isDeleted) && !Boolean.TRUE.equals(isArchived);
}
- private StorageOperationStatus fillDependenciesByLabel(String componentId, GraphVertex vertex, ComponentDependency dependency, EdgeLabelEnum label) {
- Either<List<GraphVertex>, JanusGraphOperationStatus> parentVertices = janusGraphDao.getParentVertices(vertex, label, JsonParseFlagEnum.ParseAll);
+ private StorageOperationStatus fillDependenciesByLabel(String componentId, GraphVertex vertex, ComponentDependency dependency,
+ EdgeLabelEnum label) {
+ Either<List<GraphVertex>, JanusGraphOperationStatus> parentVertices = janusGraphDao
+ .getParentVertices(vertex, label, JsonParseFlagEnum.ParseAll);
if (parentVertices.isRight() && parentVertices.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
- log.debug("Failed to fetch parent verticies by label INSTANCE_OF for vertex with id {} error {}", componentId, parentVertices.right().value());
+ log.debug("Failed to fetch parent verticies by label INSTANCE_OF for vertex with id {} error {}", componentId,
+ parentVertices.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertices.right().value());
}
if (parentVertices.isLeft()) {
- List<ComponentDependency> existIn = new ArrayList<>( );
- parentVertices.left().value().forEach(v -> handleHighestVersion(vertex, label, existIn, v) );
+ List<ComponentDependency> existIn = new ArrayList<>();
+ parentVertices.left().value().forEach(v -> handleHighestVersion(vertex, label, existIn, v));
dependency.addDependencies(existIn);
}
return StorageOperationStatus.OK;
@@ -141,41 +141,42 @@ public class UpgradeOperation extends BaseOperation {
private void handleHighestVersion(GraphVertex vertexOrigin, EdgeLabelEnum label, List<ComponentDependency> exisIn, GraphVertex containerVertex) {
Boolean isHighest = (Boolean) containerVertex.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION);
- if ( isHighest && needToAddToDependency(containerVertex) ) {
+ if (isHighest && needToAddToDependency(containerVertex)) {
JanusGraphVertex janusGraphVertex = containerVertex.getVertex();
Iterator<Edge> edges = janusGraphVertex.edges(Direction.OUT, EdgeLabelEnum.VERSION.name());
//verify that it is a last version - highest by version number
- if ( edges == null || !edges.hasNext() ){
+ if (edges == null || !edges.hasNext()) {
ComponentDependency container = fillDataFromVertex(containerVertex, vertexOrigin.getUniqueId(), label);
boolean addToDependency = true;
if (label == EdgeLabelEnum.ALLOTTED_OF) {
//in case of not full allotted chain not add to dependency list
addToDependency = findAllottedChain(containerVertex, container);
}
- if ( addToDependency ){
+ if (addToDependency) {
exisIn.add(container);
- }
+ }
}
}
}
private boolean findAllottedChain(GraphVertex vertex, ComponentDependency container) {
- Either<List<GraphVertex>, JanusGraphOperationStatus> parentVertecies = janusGraphDao.getParentVertices(vertex, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.ParseAll);
+ Either<List<GraphVertex>, JanusGraphOperationStatus> parentVertecies = janusGraphDao
+ .getParentVertices(vertex, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.ParseAll);
if (parentVertecies.isLeft()) {
List<ComponentDependency> existIn = new ArrayList<>();
parentVertecies.left().value().forEach(v -> {
Boolean isHighest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION);
- if ( isHighest && needToAddToDependency(v) ) {
- JanusGraphVertex janusGraphVertex = v.getVertex();
- Iterator<Edge> edges = janusGraphVertex.edges(Direction.OUT, EdgeLabelEnum.VERSION.name());
- //verify that it is a last version - highest by version number
- if ( edges == null || !edges.hasNext() ){
- ComponentDependency parentContainer = fillDataFromVertex(v, vertex.getUniqueId(), EdgeLabelEnum.INSTANCE_OF);
- existIn.add(parentContainer);
- }
+ if (isHighest && needToAddToDependency(v)) {
+ JanusGraphVertex janusGraphVertex = v.getVertex();
+ Iterator<Edge> edges = janusGraphVertex.edges(Direction.OUT, EdgeLabelEnum.VERSION.name());
+ //verify that it is a last version - highest by version number
+ if (edges == null || !edges.hasNext()) {
+ ComponentDependency parentContainer = fillDataFromVertex(v, vertex.getUniqueId(), EdgeLabelEnum.INSTANCE_OF);
+ existIn.add(parentContainer);
+ }
}
});
- if ( !existIn.isEmpty() ){
+ if (!existIn.isEmpty()) {
container.setDependencies(existIn);
return true;
}
@@ -191,7 +192,6 @@ public class UpgradeOperation extends BaseOperation {
container.setType((String) v.getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE));
container.setIcon((String) v.getJsonMetadataField(JsonPresentationFields.ICON));
container.setState((String) v.getMetadataProperty(GraphPropertyEnum.STATE));
-
if (edgeLabel == EdgeLabelEnum.PROXY_OF || edgeLabel == EdgeLabelEnum.ALLOTTED_OF) {
findInstanceNames(v, originId, edgeLabel, container);
}
@@ -208,17 +208,11 @@ public class UpgradeOperation extends BaseOperation {
JanusGraphVertex inVertex = (JanusGraphVertex) edge.inVertex();
String id = (String) janusGraphDao.getProperty(inVertex, GraphPropertyEnum.UNIQUE_ID.getProperty());
if (id.equals(originId)) {
- List<String> instanceOnEdge = (List<String>) janusGraphDao
- .getProperty(edge, EdgePropertyEnum.INSTANCES);
+ List<String> instanceOnEdge = (List<String>) janusGraphDao.getProperty(edge, EdgePropertyEnum.INSTANCES);
Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances();
-
if (componentInstances != null) {
- List<String> ciNames = componentInstances
- .values()
- .stream()
- .filter(ci -> instanceOnEdge.contains(ci.getUniqueId()))
- .map(ComponentInstanceDataDefinition::getName)
- .collect(Collectors.toList());
+ List<String> ciNames = componentInstances.values().stream().filter(ci -> instanceOnEdge.contains(ci.getUniqueId()))
+ .map(ComponentInstanceDataDefinition::getName).collect(Collectors.toList());
if (ciNames != null && !ciNames.isEmpty()) {
container.setInstanceNames(ciNames);
break;
@@ -229,22 +223,20 @@ public class UpgradeOperation extends BaseOperation {
}
public List<String> getInstanceIdFromAllottedEdge(String resourceId, String serviceInvariantUUID) {
- Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(resourceId);
- if ( vertexById.isLeft() ){
- GraphVertex vertexG = vertexById.left().value();
- JanusGraphVertex vertex = vertexG.getVertex();
- Iterator<Edge> edges = vertex.edges(Direction.OUT, EdgeLabelEnum.ALLOTTED_OF.name());
- while ( edges != null && edges.hasNext() ){
- Edge edge = edges.next();
- JanusGraphVertex inVertex = (JanusGraphVertex)edge.inVertex();
- String vertexInInvUUID = (String) janusGraphDao
- .getProperty(inVertex, GraphPropertyEnum.INVARIANT_UUID.getProperty());
- if ( vertexInInvUUID.equals(serviceInvariantUUID) ){
- return (List<String>) janusGraphDao.getProperty(edge, EdgePropertyEnum.INSTANCES) ;
- }
- }
- }
- return new ArrayList<>();
+ Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(resourceId);
+ if (vertexById.isLeft()) {
+ GraphVertex vertexG = vertexById.left().value();
+ JanusGraphVertex vertex = vertexG.getVertex();
+ Iterator<Edge> edges = vertex.edges(Direction.OUT, EdgeLabelEnum.ALLOTTED_OF.name());
+ while (edges != null && edges.hasNext()) {
+ Edge edge = edges.next();
+ JanusGraphVertex inVertex = (JanusGraphVertex) edge.inVertex();
+ String vertexInInvUUID = (String) janusGraphDao.getProperty(inVertex, GraphPropertyEnum.INVARIANT_UUID.getProperty());
+ if (vertexInInvUUID.equals(serviceInvariantUUID)) {
+ return (List<String>) janusGraphDao.getProperty(edge, EdgePropertyEnum.INSTANCES);
+ }
+ }
+ }
+ return new ArrayList<>();
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/exception/ToscaOperationException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/exception/ToscaOperationException.java
index b5b7da8d26..fdc42f6194 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/exception/ToscaOperationException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/exception/ToscaOperationException.java
@@ -16,7 +16,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java
index 225be207df..48597f3d59 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.utils;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.apache.commons.lang3.StringUtils.isBlank;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+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.lang3.StringUtils;
@@ -38,26 +49,14 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum;
import org.openecomp.sdc.be.model.utils.ComponentUtilities;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-import static org.apache.commons.lang3.StringUtils.isBlank;
-
public class CapabilityRequirementNameResolver {
private static final Logger log = Logger.getLogger(CapabilityRequirementNameResolver.class);
private static final String PATH_DELIMITER = ".";
- public static void updateNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, String ownerName, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
- Map<String,ToscaElement> componentCacheToRepair = new HashMap<>();
+ public static void updateNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, String ownerName,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ Map<String, ToscaElement> componentCacheToRepair = new HashMap<>();
log.debug("#updateNamesOfCalculatedCapabilitiesRequirements");
updateCalculatedCapabilitiesNames(componentCacheToRepair, toscaElement, ownerId, ownerName, originGetter);
updateCalculatedRequirementsNames(componentCacheToRepair, toscaElement, ownerId, ownerName, originGetter);
@@ -65,134 +64,115 @@ public class CapabilityRequirementNameResolver {
}
private static void updateCalculatedCapabilitiesPropertiesKeys(TopologyTemplate toscaElement, String ownerId) {
- if(calCapPropertiesExist(toscaElement, ownerId)){
- MapCapabilityProperty newProps = new MapCapabilityProperty();
- toscaElement.getCalculatedCapabilitiesProperties().get(ownerId)
- .getMapToscaDataDefinition()
- .forEach((k, v)-> updateAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps));
- if(MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) {
+ if (calCapPropertiesExist(toscaElement, ownerId)) {
+ MapCapabilityProperty newProps = new MapCapabilityProperty();
+ toscaElement.getCalculatedCapabilitiesProperties().get(ownerId).getMapToscaDataDefinition().forEach(
+ (k, v) -> updateAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps));
+ if (MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) {
toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps);
}
}
}
private static boolean calCapPropertiesExist(TopologyTemplate toscaElement, String ownerId) {
- return toscaElement.getCalculatedCapabilitiesProperties() != null
- && toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) != null
- && MapUtils.isNotEmpty(toscaElement.getCalculatedCapabilitiesProperties().get(ownerId).getMapToscaDataDefinition())
- && capabilitiesExist(toscaElement, ownerId);
+ return toscaElement.getCalculatedCapabilitiesProperties() != null && toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) != null
+ && MapUtils.isNotEmpty(toscaElement.getCalculatedCapabilitiesProperties().get(ownerId).getMapToscaDataDefinition()) && capabilitiesExist(
+ toscaElement, ownerId);
}
- private static void updateCalculatedRequirementsNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, String ownerName, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
- if(requirementsExist(toscaElement, ownerId)){
+ private static void updateCalculatedRequirementsNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement,
+ String ownerId, String ownerName,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ if (requirementsExist(toscaElement, ownerId)) {
String prefix = ownerName + PATH_DELIMITER;
repairReqNames(componentCacheToRepair, toscaElement, ownerId, originGetter);
- toscaElement.getCalculatedRequirements().get(ownerId)
- .getMapToscaDataDefinition().values().stream()
- .flatMap(l -> l.getListToscaDataDefinition().stream())
- .forEach(r -> {
- if(isRequiredToRepair(r.getName())){
- BeEcompErrorManager.getInstance()
- .logBeComponentMissingError("The empty name of the requirement was found. Id: " + r.getUniqueId() + ", ownerId: " + ownerId + ", ownerName: " + ownerName,
- toscaElement.getComponentType().getValue(), toscaElement.getName());
- }
- if(ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) {
- if(StringUtils.isNotEmpty(r.getPreviousName())){
- r.setParentName(r.getPreviousName());
- }
- r.setPreviousName(r.getName());
- }
- r.setName(prefix + r.getPreviousName());
- });
+ toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition().values().stream()
+ .flatMap(l -> l.getListToscaDataDefinition().stream()).forEach(r -> {
+ if (isRequiredToRepair(r.getName())) {
+ BeEcompErrorManager.getInstance().logBeComponentMissingError(
+ "The empty name of the requirement was found. Id: " + r.getUniqueId() + ", ownerId: " + ownerId + ", ownerName: " + ownerName,
+ toscaElement.getComponentType().getValue(), toscaElement.getName());
+ }
+ if (ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) {
+ if (StringUtils.isNotEmpty(r.getPreviousName())) {
+ r.setParentName(r.getPreviousName());
+ }
+ r.setPreviousName(r.getName());
+ }
+ r.setName(prefix + r.getPreviousName());
+ });
}
}
private static boolean requirementsExist(TopologyTemplate toscaElement, String ownerId) {
- return toscaElement.getCalculatedRequirements() != null
- && toscaElement.getCalculatedRequirements().get(ownerId) != null
- && MapUtils.isNotEmpty(toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition());
+ return toscaElement.getCalculatedRequirements() != null && toscaElement.getCalculatedRequirements().get(ownerId) != null && MapUtils
+ .isNotEmpty(toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition());
}
- private static void updateCalculatedCapabilitiesNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, String ownerName, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
- if(capabilitiesExist(toscaElement, ownerId)){
+ private static void updateCalculatedCapabilitiesNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement,
+ String ownerId, String ownerName,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ if (capabilitiesExist(toscaElement, ownerId)) {
String prefix = ownerName + PATH_DELIMITER;
repairCapNames(componentCacheToRepair, toscaElement, ownerId, originGetter);
- toscaElement.getCalculatedCapabilities().get(ownerId)
- .getMapToscaDataDefinition().values().stream()
- .flatMap(l -> l.getListToscaDataDefinition().stream())
- .forEach(c -> {
- if(isRequiredToRepair(c.getName())){
- BeEcompErrorManager.getInstance()
- .logBeComponentMissingError("The empty name of the capability was found. Id: " + c.getUniqueId() + ", ownerId: " + ownerId + ", ownerName: " + ownerName,
- toscaElement.getComponentType().getValue(), toscaElement.getName());
- }
- if(ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) {
- if(StringUtils.isNotEmpty(c.getPreviousName())){
- c.setParentName(c.getPreviousName());
- }
- c.setPreviousName(c.getName());
- }
- c.setName(prefix + c.getPreviousName());
- });
+ toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition().values().stream()
+ .flatMap(l -> l.getListToscaDataDefinition().stream()).forEach(c -> {
+ if (isRequiredToRepair(c.getName())) {
+ BeEcompErrorManager.getInstance().logBeComponentMissingError(
+ "The empty name of the capability was found. Id: " + c.getUniqueId() + ", ownerId: " + ownerId + ", ownerName: " + ownerName,
+ toscaElement.getComponentType().getValue(), toscaElement.getName());
+ }
+ if (ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) {
+ if (StringUtils.isNotEmpty(c.getPreviousName())) {
+ c.setParentName(c.getPreviousName());
+ }
+ c.setPreviousName(c.getName());
+ }
+ c.setName(prefix + c.getPreviousName());
+ });
}
}
private static boolean capabilitiesExist(TopologyTemplate toscaElement, String ownerId) {
- return toscaElement.getCalculatedCapabilities() != null
- && toscaElement.getCalculatedCapabilities().get(ownerId) != null
- && MapUtils.isNotEmpty(toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition());
+ return toscaElement.getCalculatedCapabilities() != null && toscaElement.getCalculatedCapabilities().get(ownerId) != null && MapUtils
+ .isNotEmpty(toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition());
}
- private static void repairCapNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ private static void repairCapNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
log.debug("#repairCapNames");
- boolean emptyNameFound = toscaElement.getCalculatedCapabilities() != null
- && toscaElement.getCalculatedCapabilities().get(ownerId) != null
- && toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition() != null
- && toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition().values()
- .stream()
- .filter(Objects::nonNull)
- .flatMap(l -> l.getListToscaDataDefinition().stream())
- .filter(Objects::nonNull)
- .anyMatch(c -> isRequiredToRepair(c.getName()));
-
- ComponentInstanceDataDefinition instance = toscaElement.getComponentInstances() != null ?
- toscaElement.getComponentInstances().get(ownerId) : null;
- if(instance != null && emptyNameFound){
+ boolean emptyNameFound = toscaElement.getCalculatedCapabilities() != null && toscaElement.getCalculatedCapabilities().get(ownerId) != null
+ && toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition() != null && toscaElement.getCalculatedCapabilities()
+ .get(ownerId).getMapToscaDataDefinition().values().stream().filter(Objects::nonNull).flatMap(l -> l.getListToscaDataDefinition().stream())
+ .filter(Objects::nonNull).anyMatch(c -> isRequiredToRepair(c.getName()));
+ ComponentInstanceDataDefinition instance =
+ toscaElement.getComponentInstances() != null ? toscaElement.getComponentInstances().get(ownerId) : null;
+ if (instance != null && emptyNameFound) {
log.debug("#repairCapNames - Going to repair the name of the capability for the owner {}. ", ownerId);
- toscaElement.getCalculatedCapabilities().get(ownerId)
- .getMapToscaDataDefinition().values()
- .stream()
- .flatMap(l -> l.getListToscaDataDefinition().stream())
- .forEach(c-> repairCapName(componentCacheToRepair, instance, c, originGetter));
+ toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition().values().stream()
+ .flatMap(l -> l.getListToscaDataDefinition().stream()).forEach(c -> repairCapName(componentCacheToRepair, instance, c, originGetter));
}
}
- private static void repairReqNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ private static void repairReqNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
log.debug("#repairReqNames");
- boolean emptyNameFound = toscaElement.getCalculatedRequirements() != null
- && toscaElement.getCalculatedRequirements().get(ownerId) != null
- && toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition() != null
- && toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition().values()
- .stream()
- .filter(Objects::nonNull)
- .flatMap(l -> l.getListToscaDataDefinition().stream())
- .filter(Objects::nonNull)
- .anyMatch(r -> isRequiredToRepair(r.getName()));
-
- ComponentInstanceDataDefinition instance = toscaElement.getComponentInstances() != null ?
- toscaElement.getComponentInstances().get(ownerId) : null;
- if(instance != null && emptyNameFound){
+ boolean emptyNameFound = toscaElement.getCalculatedRequirements() != null && toscaElement.getCalculatedRequirements().get(ownerId) != null
+ && toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition() != null && toscaElement.getCalculatedRequirements()
+ .get(ownerId).getMapToscaDataDefinition().values().stream().filter(Objects::nonNull).flatMap(l -> l.getListToscaDataDefinition().stream())
+ .filter(Objects::nonNull).anyMatch(r -> isRequiredToRepair(r.getName()));
+ ComponentInstanceDataDefinition instance =
+ toscaElement.getComponentInstances() != null ? toscaElement.getComponentInstances().get(ownerId) : null;
+ if (instance != null && emptyNameFound) {
log.debug("#repairReqNames - Going to repair the name of the requirement for the owner {}. ", ownerId);
- toscaElement.getCalculatedRequirements().get(ownerId)
- .getMapToscaDataDefinition().values()
- .stream()
- .flatMap(l -> l.getListToscaDataDefinition().stream())
- .forEach(r-> repairReqName(componentCacheToRepair, instance, r, originGetter));
+ toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition().values().stream()
+ .flatMap(l -> l.getListToscaDataDefinition().stream()).forEach(r -> repairReqName(componentCacheToRepair, instance, r, originGetter));
}
}
- private static void repairCapName(Map<String, ToscaElement> componentCacheToRepair, ComponentInstanceDataDefinition instance, CapabilityDataDefinition capability, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
- if(isRequiredToRepair(capability.getName())){
+ private static void repairCapName(Map<String, ToscaElement> componentCacheToRepair, ComponentInstanceDataDefinition instance,
+ CapabilityDataDefinition capability, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ if (isRequiredToRepair(capability.getName())) {
log.debug("#repairTopologyTemplateCapName - Going to build the name for the capability: ", capability.getUniqueId());
buildSetCapName(componentCacheToRepair, capability, instance, originGetter);
}
@@ -200,157 +180,161 @@ public class CapabilityRequirementNameResolver {
private static boolean isRequiredToRepair(String name) {
boolean isRequiredToRepair = StringUtils.isEmpty(name) || name.endsWith(".null") || name.contains(".null.");
- if(isRequiredToRepair){
- log.debug("#isRequiredToRepair - The name {} should be repaired. ", name) ;
- } else{
- log.debug("#isRequiredToRepair - The name {} should not be repaired. ", name) ;
+ if (isRequiredToRepair) {
+ log.debug("#isRequiredToRepair - The name {} should be repaired. ", name);
+ } else {
+ log.debug("#isRequiredToRepair - The name {} should not be repaired. ", name);
}
return isRequiredToRepair;
}
- private static void repairReqName(Map<String, ToscaElement> componentCacheToRepair, ComponentInstanceDataDefinition instance, RequirementDataDefinition requirement, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
- if(isRequiredToRepair(requirement.getName())){
+ private static void repairReqName(Map<String, ToscaElement> componentCacheToRepair, ComponentInstanceDataDefinition instance,
+ RequirementDataDefinition requirement, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ if (isRequiredToRepair(requirement.getName())) {
log.debug("#repairTopologyTemplateCapName - Going to build the name for the requirement: ", requirement.getUniqueId());
buildSetReqName(componentCacheToRepair, requirement, instance, originGetter);
}
}
- private static void updateAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) {
+ private static void updateAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties,
+ MapListCapabilityDataDefinition calculatedCapabilities,
+ MapCapabilityProperty newProps) {
String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM);
String capType = key[key.length - 2];
String capName = key[key.length - 1];
- Optional<CapabilityDataDefinition> foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType)
- .getListToscaDataDefinition().stream()
- .filter(c -> StringUtils.isNotEmpty(c.getPreviousName())&& c.getPreviousName().equals(capName))
- .findFirst();
+ Optional<CapabilityDataDefinition> foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType).getListToscaDataDefinition()
+ .stream().filter(c -> StringUtils.isNotEmpty(c.getPreviousName()) && c.getPreviousName().equals(capName)).findFirst();
foundCapOpt.ifPresent(capabilityDataDefinition -> key[key.length - 1] = capabilityDataDefinition.getName());
- newProps.put(buildCaLCapPropKey(key),properties);
+ newProps.put(buildCaLCapPropKey(key), properties);
}
- public static void revertNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
- Map<String,ToscaElement> componentCacheToRepair = new HashMap<>();
+ public static void revertNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ Map<String, ToscaElement> componentCacheToRepair = new HashMap<>();
log.debug("#revertNamesOfCalculatedCapabilitiesRequirements");
revertCalculatedCapabilitiesPropertiesKeys(componentCacheToRepair, toscaElement, ownerId, originGetter);
revertCalculatedCapabilitiesNames(toscaElement, ownerId);
revertCalculatedRequirementsNames(componentCacheToRepair, toscaElement, ownerId, originGetter);
}
- private static void revertCalculatedCapabilitiesPropertiesKeys(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ private static void revertCalculatedCapabilitiesPropertiesKeys(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement,
+ String ownerId,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
repairCapNames(componentCacheToRepair, toscaElement, ownerId, originGetter);
- if(calCapPropertiesExist(toscaElement, ownerId)){
- MapCapabilityProperty newProps = new MapCapabilityProperty();
- toscaElement.getCalculatedCapabilitiesProperties().get(ownerId)
- .getMapToscaDataDefinition()
- .forEach((k,v) -> revertAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps));
- if(MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) {
+ if (calCapPropertiesExist(toscaElement, ownerId)) {
+ MapCapabilityProperty newProps = new MapCapabilityProperty();
+ toscaElement.getCalculatedCapabilitiesProperties().get(ownerId).getMapToscaDataDefinition().forEach(
+ (k, v) -> revertAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps));
+ if (MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) {
toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps);
}
}
}
- private static void revertCalculatedRequirementsNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ private static void revertCalculatedRequirementsNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement,
+ String ownerId, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
repairReqNames(componentCacheToRepair, toscaElement, ownerId, originGetter);
- if(requirementsExist(toscaElement, ownerId)){
- toscaElement.getCalculatedRequirements().get(ownerId)
- .getMapToscaDataDefinition().values().stream()
- .flatMap(l -> l.getListToscaDataDefinition().stream())
- .forEach(CapabilityRequirementNameResolver::revertReqNames);
+ if (requirementsExist(toscaElement, ownerId)) {
+ toscaElement.getCalculatedRequirements().get(ownerId).getMapToscaDataDefinition().values().stream()
+ .flatMap(l -> l.getListToscaDataDefinition().stream()).forEach(CapabilityRequirementNameResolver::revertReqNames);
}
}
private static void revertReqNames(RequirementDataDefinition requirement) {
- if(StringUtils.isNotEmpty(requirement.getPreviousName())) {
+ if (StringUtils.isNotEmpty(requirement.getPreviousName())) {
requirement.setName(requirement.getPreviousName());
requirement.setPreviousName(requirement.getParentName());
}
}
private static void revertCalculatedCapabilitiesNames(TopologyTemplate toscaElement, String ownerId) {
- if(capabilitiesExist(toscaElement, ownerId)){
- toscaElement.getCalculatedCapabilities().get(ownerId)
- .getMapToscaDataDefinition().values().stream()
- .flatMap(l -> l.getListToscaDataDefinition().stream())
- .forEach(CapabilityRequirementNameResolver::revertCapNames);
+ if (capabilitiesExist(toscaElement, ownerId)) {
+ toscaElement.getCalculatedCapabilities().get(ownerId).getMapToscaDataDefinition().values().stream()
+ .flatMap(l -> l.getListToscaDataDefinition().stream()).forEach(CapabilityRequirementNameResolver::revertCapNames);
}
}
private static void revertCapNames(CapabilityDataDefinition capability) {
- if(StringUtils.isNotEmpty(capability.getPreviousName())) {
+ if (StringUtils.isNotEmpty(capability.getPreviousName())) {
capability.setName(capability.getPreviousName());
capability.setPreviousName(capability.getParentName());
}
}
- private static void revertAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) {
+ private static void revertAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties,
+ MapListCapabilityDataDefinition calculatedCapabilities,
+ MapCapabilityProperty newProps) {
String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM);
String capType = key[key.length - 2];
String capName = key[key.length - 1];
- Optional<CapabilityDataDefinition> foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType)
- .getListToscaDataDefinition().stream()
- .filter(c -> c.getName().equals(capName) && StringUtils.isNotEmpty(c.getPreviousName()))
- .findFirst();
+ Optional<CapabilityDataDefinition> foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType).getListToscaDataDefinition()
+ .stream().filter(c -> c.getName().equals(capName) && StringUtils.isNotEmpty(c.getPreviousName())).findFirst();
foundCapOpt.ifPresent(capabilityDataDefinition -> key[key.length - 1] = capabilityDataDefinition.getPreviousName());
newProps.put(buildCaLCapPropKey(key), properties);
}
private static String buildCaLCapPropKey(String[] keyArray) {
StringBuilder key = new StringBuilder();
- for(int i = 0; i< keyArray.length; ++i){
+ for (int i = 0; i < keyArray.length; ++i) {
key.append(keyArray[i]);
- if(i < keyArray.length - 1){
+ if (i < keyArray.length - 1) {
key.append(ModelConverter.CAP_PROP_DELIM);
}
}
return key.toString();
}
- private static void buildSetCapName(Map<String, ToscaElement> componentsCache, CapabilityDataDefinition capability, ComponentInstanceDataDefinition instance, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
- List<String> reducedPath = capability.getOwnerId() !=null ? getReducedPathByOwner(capability.getPath() , capability.getOwnerId() ) : getReducedPath(capability.getPath()) ;
+ private static void buildSetCapName(Map<String, ToscaElement> componentsCache, CapabilityDataDefinition capability,
+ ComponentInstanceDataDefinition instance,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ List<String> reducedPath = capability.getOwnerId() != null ? getReducedPathByOwner(capability.getPath(), capability.getOwnerId())
+ : getReducedPath(capability.getPath());
log.debug("reducedPath for ownerId {}, reducedPath {} ", capability.getOwnerId(), reducedPath);
reducedPath.remove(reducedPath.size() - 1);
ToscaElement originComponent = getOriginComponent(componentsCache, instance, originGetter);
- String name = isRequiredToRepair(capability.getParentName()) ?
- extractNameFromUniqueId(capability.getUniqueId()) : capability.getParentName();
+ String name = isRequiredToRepair(capability.getParentName()) ? extractNameFromUniqueId(capability.getUniqueId()) : capability.getParentName();
StringBuilder repairedName = buildSubstitutedName(componentsCache, originComponent, reducedPath, originGetter);
log.debug("#buildSetCapName - The name for the capability was built: {}", repairedName);
-
capability.setName(repairedName.append(name).toString());
- if(isRequiredToRepair(capability.getPreviousName())){
+ if (isRequiredToRepair(capability.getPreviousName())) {
capability.setPreviousName(capability.getName().substring(capability.getName().indexOf(PATH_DELIMITER) + 1));
}
- if(isRequiredToRepair(capability.getParentName())){
+ if (isRequiredToRepair(capability.getParentName())) {
capability.setParentName(name);
}
}
- private static void buildSetReqName(Map<String, ToscaElement> componentsCache, RequirementDataDefinition requirement, ComponentInstanceDataDefinition instance, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
- List<String> reducedPath = requirement.getOwnerId() !=null ? getReducedPathByOwner(requirement.getPath() , requirement.getOwnerId() ) : getReducedPath(requirement.getPath()) ;
+ private static void buildSetReqName(Map<String, ToscaElement> componentsCache, RequirementDataDefinition requirement,
+ ComponentInstanceDataDefinition instance,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ List<String> reducedPath = requirement.getOwnerId() != null ? getReducedPathByOwner(requirement.getPath(), requirement.getOwnerId())
+ : getReducedPath(requirement.getPath());
log.debug("reducedPath for ownerId {}, reducedPath {} ", requirement.getOwnerId(), reducedPath);
reducedPath.remove(reducedPath.size() - 1);
ToscaElement originComponent = getOriginComponent(componentsCache, instance, originGetter);
- String name = isRequiredToRepair(requirement.getParentName()) ?
- extractNameFromUniqueId(requirement.getUniqueId()) : requirement.getParentName();
-
+ String name =
+ isRequiredToRepair(requirement.getParentName()) ? extractNameFromUniqueId(requirement.getUniqueId()) : requirement.getParentName();
StringBuilder repairedName = buildSubstitutedName(componentsCache, originComponent, reducedPath, originGetter);
log.debug("#buildSetReqName - The name for the capability was built: ", repairedName);
requirement.setName(repairedName.append(name).toString());
- if(isRequiredToRepair(requirement.getPreviousName())){
+ if (isRequiredToRepair(requirement.getPreviousName())) {
requirement.setPreviousName(requirement.getName().substring(requirement.getName().indexOf(PATH_DELIMITER) + 1));
}
- if(isRequiredToRepair(requirement.getParentName())){
+ if (isRequiredToRepair(requirement.getParentName())) {
requirement.setParentName(name);
}
}
private static String extractNameFromUniqueId(String uniqueId) {
String[] uid = uniqueId.split("\\.");
- return uid [uid.length - 1];
+ return uid[uid.length - 1];
}
- private static StringBuilder buildSubstitutedName(Map<String, ToscaElement> componentsCache, ToscaElement originComponent, List<String> path, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ private static StringBuilder buildSubstitutedName(Map<String, ToscaElement> componentsCache, ToscaElement originComponent, List<String> path,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
StringBuilder substitutedName = new StringBuilder();
log.debug("#buildSubstitutedName");
- if(isNotEmpty(path) && isTopologyTemplateNotCvfc(originComponent)){
+ if (isNotEmpty(path) && isTopologyTemplateNotCvfc(originComponent)) {
log.debug("#buildSubstitutedName");
List<String> reducedPath = getReducedPath(path);
Collections.reverse(reducedPath);
@@ -363,8 +347,9 @@ public class CapabilityRequirementNameResolver {
return originComponent.getToscaType() == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE && originComponent.getResourceType() != ResourceTypeEnum.CVFC;
}
- private static ToscaElement getOriginComponent(Map<String, ToscaElement> componentsCache, ComponentInstanceDataDefinition instance, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
- if(componentsCache.containsKey(getActualComponentUid(instance))){
+ private static ToscaElement getOriginComponent(Map<String, ToscaElement> componentsCache, ComponentInstanceDataDefinition instance,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ if (componentsCache.containsKey(getActualComponentUid(instance))) {
return componentsCache.get(getActualComponentUid(instance));
}
ToscaElement origin = originGetter.apply(instance);
@@ -380,43 +365,49 @@ public class CapabilityRequirementNameResolver {
return path.stream().distinct().collect(Collectors.toList());
}
- private static void appendNameRecursively(Map<String, ToscaElement> componentsCache, ToscaElement originComponent, Iterator<String> instanceIdIter, StringBuilder substitutedName, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
+ private static void appendNameRecursively(Map<String, ToscaElement> componentsCache, ToscaElement originComponent,
+ Iterator<String> instanceIdIter, StringBuilder substitutedName,
+ Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) {
log.debug("#appendNameRecursively");
- if(isTopologyTemplateNotCvfc(originComponent)
- && MapUtils.isNotEmpty(((TopologyTemplate)originComponent).getComponentInstances()) && instanceIdIter.hasNext()){
-
+ if (isTopologyTemplateNotCvfc(originComponent) && MapUtils.isNotEmpty(((TopologyTemplate) originComponent).getComponentInstances())
+ && instanceIdIter.hasNext()) {
String ownerId = instanceIdIter.next();
- Optional<ComponentInstanceDataDefinition> instanceOpt = ((TopologyTemplate)originComponent).getComponentInstances().values().stream().filter(i -> i.getUniqueId().equals(ownerId)).findFirst();
- if(instanceOpt.isPresent()){
+ Optional<ComponentInstanceDataDefinition> instanceOpt = ((TopologyTemplate) originComponent).getComponentInstances().values().stream()
+ .filter(i -> i.getUniqueId().equals(ownerId)).findFirst();
+ if (instanceOpt.isPresent()) {
substitutedName.append(instanceOpt.get().getNormalizedName()).append(PATH_DELIMITER);
ToscaElement getOriginRes = getOriginComponent(componentsCache, instanceOpt.get(), originGetter);
appendNameRecursively(componentsCache, getOriginRes, instanceIdIter, substitutedName, originGetter);
- } else if(MapUtils.isNotEmpty(((TopologyTemplate)originComponent).getGroups())){
- Optional<GroupDataDefinition> groupOpt = ((TopologyTemplate)originComponent).getGroups().values().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst();
+ } else if (MapUtils.isNotEmpty(((TopologyTemplate) originComponent).getGroups())) {
+ Optional<GroupDataDefinition> groupOpt = ((TopologyTemplate) originComponent).getGroups().values().stream()
+ .filter(g -> g.getUniqueId().equals(ownerId)).findFirst();
groupOpt.ifPresent(groupDataDefinition -> substitutedName.append(groupDataDefinition.getName()).append(PATH_DELIMITER));
} else {
- log.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, originComponent.getUniqueId());
+ log.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId,
+ originComponent.getUniqueId());
}
}
}
- private static List<String> getReducedPathByOwner(List<String> path , String ownerId) {
+ private static List<String> getReducedPathByOwner(List<String> path, String ownerId) {
log.debug("ownerId {}, path {} ", ownerId, path);
- if ( CollectionUtils.isEmpty(path) ){
+ if (CollectionUtils.isEmpty(path)) {
log.debug("cannot perform reduce by owner, path to component is empty");
return path;
}
- if ( isBlank(ownerId) ){
+ if (isBlank(ownerId)) {
log.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 static String dropLast( String path, String delimiter ) {
- if (isBlank(path) || isBlank(delimiter)){
+
+ private static String dropLast(String path, String delimiter) {
+ if (isBlank(path) || isBlank(delimiter)) {
return path;
}
return path.substring(0, path.lastIndexOf(delimiter));
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapper.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapper.java
index a20eb4dc14..7b1712db23 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapper.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/IdMapper.java
@@ -17,9 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.utils;
+import java.util.Map;
+import java.util.Optional;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
@@ -29,9 +30,6 @@ import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Component;
-import java.util.Map;
-import java.util.Optional;
-
/**
* Created by yavivi on 12/02/2018.
*/
@@ -53,30 +51,25 @@ public class IdMapper {
try {
Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) serviceVertex.getJson();
CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
-
Optional<ComponentInstanceDataDefinition> componentInstanceDataDefinitionOptional;
if (fromCompName) {
- componentInstanceDataDefinitionOptional = compositionDataDefinition.getComponentInstances().values()
- .stream().filter(c -> c.getNormalizedName().equals(componentUniqueIdOrName)).findAny();
-
+ componentInstanceDataDefinitionOptional = compositionDataDefinition.getComponentInstances().values().stream()
+ .filter(c -> c.getNormalizedName().equals(componentUniqueIdOrName)).findAny();
if (componentInstanceDataDefinitionOptional.isPresent()) {
result = componentInstanceDataDefinitionOptional.get().getUniqueId();
log.debug("Component Instance Unique Id = {}", result);
}
} else {
- componentInstanceDataDefinitionOptional = compositionDataDefinition.getComponentInstances().values()
- .stream().filter(c -> c.getUniqueId().equals(componentUniqueIdOrName)).findAny();
-
+ componentInstanceDataDefinitionOptional = compositionDataDefinition.getComponentInstances().values().stream()
+ .filter(c -> c.getUniqueId().equals(componentUniqueIdOrName)).findAny();
if (componentInstanceDataDefinitionOptional.isPresent()) {
result = componentInstanceDataDefinitionOptional.get().getNormalizedName();
log.debug("Component Instance Normalized Name = {}", result);
}
}
} catch (Exception e) {
- log.error(EcompLoggerErrorCode.DATA_ERROR, "Failed to map UUID or Normalized name of {}",
- componentUniqueIdOrName, e);
+ log.error(EcompLoggerErrorCode.DATA_ERROR, "Failed to map UUID or Normalized name of {}", componentUniqueIdOrName, e);
}
return result;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java
index 08f672b4c8..f26e0a39ea 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.jsonjanusgraph.utils;
import com.google.common.collect.Lists;
@@ -130,12 +129,12 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
public class ModelConverter {
- private ModelConverter() {
- }
-
public static final String CAP_PROP_DELIM = "#";
private static final Logger log = Logger.getLogger(ModelConverter.class);
+ private ModelConverter() {
+ }
+
@SuppressWarnings("unchecked")
public static <T extends ToscaElement> T convertToToscaElement(Component component) {
if (isAtomicComponent(component)) {
@@ -197,45 +196,25 @@ public class ModelConverter {
private static Service convertToService(ToscaElement toscaElement) {
Service service = new Service();
convertComponentFields(service, toscaElement);
-
convertServiceSpecificFields(toscaElement, service);
-
TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement;
-
convertComponentInstances(topologyTemplate, service);
-
convertInputs(topologyTemplate, service);
-
convertOutputs(topologyTemplate, service);
-
convertProperties(topologyTemplate, service);
-
convertPolicies(topologyTemplate, service);
-
convertAttributesToComponent(topologyTemplate, service);
-
convertGroups(topologyTemplate, service);
-
setCapabilitiesToComponentAndGroups(topologyTemplate, service);
-
convertPolicies(topologyTemplate, service);
-
convertRelations(topologyTemplate, service);
-
convertArtifacts(topologyTemplate, service);
-
convertServiceApiArtifacts(topologyTemplate, service);
-
convertServicePaths(topologyTemplate, service);
-
convertServiceInterfaces(topologyTemplate, service);
-
convertDataTypes(topologyTemplate, service);
-
convertNodeFiltersComponents(topologyTemplate, service);
-
convertSubstitutionFiltersComponents(topologyTemplate, service);
-
setCapabilitiesToComponent(topologyTemplate, service);
setRequirementsToComponent(topologyTemplate, service);
return service;
@@ -243,21 +222,17 @@ public class ModelConverter {
private static void convertServiceSpecificFields(ToscaElement toscaElement, Service service) {
service.setProjectCode((String) toscaElement.getMetadataValue(JsonPresentationFields.PROJECT_CODE));
- service.setDistributionStatus(DistributionStatusEnum
- .findState((String) toscaElement.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS)));
- service.setEcompGeneratedNaming(
- (Boolean) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.ECOMP_GENERATED_NAMING, true));
- service.setNamingPolicy((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.NAMING_POLICY,
- StringUtils.EMPTY));
- service.setEnvironmentContext(
- (String) toscaElement.getMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT));
+ service.setDistributionStatus(
+ DistributionStatusEnum.findState((String) toscaElement.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS)));
+ service.setEcompGeneratedNaming((Boolean) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.ECOMP_GENERATED_NAMING, true));
+ service.setNamingPolicy((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.NAMING_POLICY, StringUtils.EMPTY));
+ service.setEnvironmentContext((String) toscaElement.getMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT));
service.setInstantiationType((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.INSTANTIATION_TYPE, StringUtils.EMPTY));
}
private static Resource convertToResource(ToscaElement toscaElement) {
Resource resource = new Resource();
convertComponentFields(resource, toscaElement);
-
resource.setResourceType(toscaElement.getResourceType());
if (toscaElement.getToscaType() == ToscaElementTypeEnum.NODE_TYPE) {
NodeType nodeType = (NodeType) toscaElement;
@@ -274,7 +249,6 @@ public class ModelConverter {
convertRequirements(nodeType, resource);
convertInterfaces(nodeType, resource);
convertDataTypes(nodeType, resource);
-
} else {
TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement;
if (resource.getResourceType() == ResourceTypeEnum.VF || resource.getResourceType() == ResourceTypeEnum.PNF) {
@@ -300,7 +274,6 @@ public class ModelConverter {
}
convertArtifacts(toscaElement, resource);
convertAdditionalInformation(toscaElement, resource);
-
return resource;
}
@@ -351,37 +324,24 @@ public class ModelConverter {
* @param component
*/
public static void convertComponentInstances(TopologyTemplate topologyTemplate, Component component) {
-
if (MapUtils.isNotEmpty(topologyTemplate.getComponentInstances())) {
-
setComponentInstancesAttributesToComponent(topologyTemplate, component);
-
setComponentInstancesPropertiesToComponent(topologyTemplate, component);
-
setComponentInstancesInputsToComponent(topologyTemplate, component);
-
setComponentInstancesOutputsToComponent(topologyTemplate, component);
-
setComponentInstancesToComponent(topologyTemplate, component);
-
setComponentInstancesCapabilitiesToComponentAndCI(topologyTemplate, component);
-
setComponentInstancesRequirementsToComponent(topologyTemplate, component);
-
setComponentInstancesArtifactsToComponent(topologyTemplate, component);
-
setComponentInstancesInterfacesToComponent(topologyTemplate, component);
-
}
}
private static void setComponentInstancesArtifactsToComponent(TopologyTemplate topologyTemplate, Component component) {
Map<String, MapArtifactDataDefinition> instDeploymentArtifacts = topologyTemplate.getInstDeploymentArtifacts();
Map<String, MapArtifactDataDefinition> instanceArtifacts = topologyTemplate.getInstanceArtifacts();
-
setComponentInstancesDeploymentArtifactsToComponent(instDeploymentArtifacts, component);
setComponentInstancesInformationalArtifactsToComponent(instanceArtifacts, component);
-
}
public static void setComponentInstancesInformationalArtifactsToComponent(Map<String, MapArtifactDataDefinition> instanceArtifacts,
@@ -394,7 +354,6 @@ public class ModelConverter {
Map<String, ArtifactDataDefinition> mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition();
Map<String, ArtifactDefinition> deplArt = mapToscaDataDefinition.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue())));
-
ci.get().setArtifacts(deplArt);
}
});
@@ -411,7 +370,6 @@ public class ModelConverter {
Map<String, ArtifactDataDefinition> mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition();
Map<String, ArtifactDefinition> deplArt = mapToscaDataDefinition.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue())));
-
ci.get().setDeploymentArtifacts(deplArt);
}
});
@@ -419,17 +377,11 @@ public class ModelConverter {
}
public static void convertComponentInstances(Component component, TopologyTemplate topologyTemplate) {
-
if (!CollectionUtils.isEmpty(component.getComponentInstances())) {
-
setComponentInstancesAttributesToTopologyTemplate(component, topologyTemplate);
-
setComponentInstancesPropertiesToTopologyTemplate(component, topologyTemplate);
-
setComponentInstancesInputsToTopologyTemplate(component, topologyTemplate);
-
setComponentInstancesToTopologyTemplate(component, topologyTemplate);
-
setComponentInstancesArtifactsToTopologyTemplate(component, topologyTemplate);
}
}
@@ -439,12 +391,10 @@ public class ModelConverter {
List<RequirementCapabilityRelDef> componentRelations;
if (relations != null && !relations.isEmpty()) {
componentRelations = relations.values().stream().map(ModelConverter::convertRelation).collect(Collectors.toList());
-
} else {
componentRelations = new ArrayList<>();
}
component.setComponentInstancesRelations(componentRelations);
-
}
public static RequirementCapabilityRelDef convertRelation(RelationshipInstDataDefinition relation) {
@@ -452,13 +402,11 @@ public class ModelConverter {
requirementCapabilityRelDef.setFromNode(relation.getFromId());
requirementCapabilityRelDef.setToNode(relation.getToId());
requirementCapabilityRelDef.setOriginUI(BooleanUtils.isTrue(relation.isOriginUI()));
-
CapabilityRequirementRelationship rel = new CapabilityRequirementRelationship();
RelationshipInfo relationshipPair = getRelationshipInfo(relation);
rel.setRelation(relationshipPair);
rel.setOperations(convertToOperations(relation.getInterfaces()));
requirementCapabilityRelDef.setRelationships(Arrays.asList(rel));
-
return requirementCapabilityRelDef;
}
@@ -471,8 +419,7 @@ public class ModelConverter {
if (MapUtils.isEmpty(interfaceDataDefinition.getOperations())) {
continue;
}
- for (final Entry<String, OperationDataDefinition> operationEntry :
- interfaceDataDefinition.getOperations().entrySet()) {
+ for (final Entry<String, OperationDataDefinition> operationEntry : interfaceDataDefinition.getOperations().entrySet()) {
final OperationUi operationUi = new OperationUi();
operationUi.setOperationType(operationEntry.getKey());
operationUi.setInterfaceType(interfaceDataDefinition.getType());
@@ -481,11 +428,9 @@ public class ModelConverter {
if (implementation != null) {
operationUi.setImplementation(implementation.getArtifactName());
}
-
final ListDataDefinition<OperationInputDefinition> inputs = operationDataDefinition.getInputs();
if (inputs != null && !inputs.isEmpty()) {
- final List<OperationInputDefinition> operationInputDefinitionList =
- inputs.getListToscaDataDefinition();
+ final List<OperationInputDefinition> operationInputDefinitionList = inputs.getListToscaDataDefinition();
operationInputDefinitionList.forEach(operationInputDefinition -> {
final PropertyAssignmentUi propertyAssignmentUi = new PropertyAssignmentUi();
propertyAssignmentUi.setName(operationInputDefinition.getLabel());
@@ -506,29 +451,21 @@ public class ModelConverter {
*/
private static RelationshipInfo getRelationshipInfo(RelationshipInstDataDefinition relation) {
RelationshipInfo relationshipPair = new RelationshipInfo();
-
relationshipPair.setId(relation.getUniqueId());
-
relationshipPair.setCapabilityOwnerId(relation.getCapabilityOwnerId());
relationshipPair.setCapabilityUid(relation.getCapabilityId());
relationshipPair.setCapability(relation.getCapability());
-
relationshipPair.setRequirementOwnerId(relation.getRequirementOwnerId());
relationshipPair.setRequirementUid(relation.getRequirementId());
relationshipPair.setRequirement(relation.getRequirement());
-
RelationshipImpl relationship = new RelationshipImpl();
relationship.setType(relation.getType());
relationshipPair.setRelationships(relationship);
-
return relationshipPair;
}
-
public static List<RelationshipInstDataDefinition> convertRelationToToscaRelation(RequirementCapabilityRelDef relation) {
-
List<RelationshipInstDataDefinition> relationsList = new ArrayList<>();
-
List<CapabilityRequirementRelationship> relationship = relation.getRelationships();
relationship.forEach(p -> {
RelationshipInstDataDefinition requirementCapabilityRelDef = new RelationshipInstDataDefinition();
@@ -545,7 +482,6 @@ public class ModelConverter {
requirementCapabilityRelDef.setOriginUI(relation.isOriginUI());
relationsList.add(requirementCapabilityRelDef);
});
-
return relationsList;
}
@@ -561,42 +497,34 @@ public class ModelConverter {
private static void convertGroupsCapabilities(Component component, TopologyTemplate topologyTemplate) {
if (groupsCapabilitiesExist(component)) {
- component.getGroups()
- .stream()
- .filter(g -> MapUtils.isNotEmpty(g.getCapabilities()))
+ component.getGroups().stream().filter(g -> MapUtils.isNotEmpty(g.getCapabilities()))
.forEach(g -> addCapabilities(topologyTemplate, g.getCapabilities(), g.getUniqueId()));
}
}
private static void convertTopologyTemplateCapabilities(Component component, ToscaElement toscaElement) {
Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
-
Map<String, ListCapabilityDataDefinition> toscaCapMap = new HashMap<>();
Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>();
-
if (MapUtils.isNotEmpty(capabilities)) {
capabilities.forEach((s, caps) -> {
- if (CollectionUtils.isNotEmpty(caps)) {
- List<CapabilityDataDefinition> capList = caps.stream().filter(capabilityDefinition -> capabilityDefinition.getOwnerId()
- .equals(component.getUniqueId())).map(CapabilityDataDefinition::new).collect(Collectors.toList());
-
- populateCapabilityMap(toscaCapMap, toscaCapPropMap, s, caps, capList);
- }
+ if (CollectionUtils.isNotEmpty(caps)) {
+ List<CapabilityDataDefinition> capList = caps.stream()
+ .filter(capabilityDefinition -> capabilityDefinition.getOwnerId().equals(component.getUniqueId()))
+ .map(CapabilityDataDefinition::new).collect(Collectors.toList());
+ populateCapabilityMap(toscaCapMap, toscaCapPropMap, s, caps, capList);
}
- );
-
+ });
toscaElement.setCapabilities(toscaCapMap);
toscaElement.setCapabilitiesProperties(toscaCapPropMap);
}
}
private static void populateCapabilityMap(Map<String, ListCapabilityDataDefinition> toscaCapMap,
- Map<String, MapPropertiesDataDefinition> toscaCapPropMap,
- String s, List<CapabilityDefinition> caps,
+ Map<String, MapPropertiesDataDefinition> toscaCapPropMap, String s, List<CapabilityDefinition> caps,
List<CapabilityDataDefinition> capList) {
ListCapabilityDataDefinition listCapabilityDataDefinition = new ListCapabilityDataDefinition(capList);
toscaCapMap.put(s, listCapabilityDataDefinition);
-
for (CapabilityDefinition cap : caps) {
List<ComponentInstanceProperty> capPrps = cap.getProperties();
if (CollectionUtils.isNotEmpty(capPrps)) {
@@ -613,29 +541,24 @@ public class ModelConverter {
private static void convertTopologyTemplateRequirements(Component component, ToscaElement toscaElement) {
Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
-
Map<String, ListRequirementDataDefinition> toscaReqMap = new HashMap<>();
-
if (MapUtils.isNotEmpty(requirements)) {
requirements.forEach((s, reqs) -> {
- if (CollectionUtils.isNotEmpty(reqs)) {
- List<RequirementDataDefinition> reqList = reqs.stream().filter(requirementDefinition -> requirementDefinition.getOwnerId()
- .equals(component.getUniqueId())).map(RequirementDataDefinition::new).collect(Collectors.toList());
-
- ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList);
- toscaReqMap.put(s, listRequirementDataDefinition);
- }
+ if (CollectionUtils.isNotEmpty(reqs)) {
+ List<RequirementDataDefinition> reqList = reqs.stream()
+ .filter(requirementDefinition -> requirementDefinition.getOwnerId().equals(component.getUniqueId()))
+ .map(RequirementDataDefinition::new).collect(Collectors.toList());
+ ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList);
+ toscaReqMap.put(s, listRequirementDataDefinition);
}
- );
+ });
toscaElement.setRequirements(toscaReqMap);
}
}
private static void convertComponentInstancesCapabilities(Component component, TopologyTemplate topologyTemplate) {
if (componentInstancesCapabilitiesExist(component)) {
- component.getComponentInstances()
- .stream()
- .filter(i -> MapUtils.isNotEmpty(i.getCapabilities()))
+ component.getComponentInstances().stream().filter(i -> MapUtils.isNotEmpty(i.getCapabilities()))
.forEach(i -> addCapabilities(topologyTemplate, i.getCapabilities(), i.getUniqueId()));
}
}
@@ -654,22 +577,17 @@ public class ModelConverter {
}
private static boolean componentInstancesCapabilitiesExist(Component component) {
- return component.getCapabilities() != null && component.getComponentInstances() != null
- && component.getComponentInstances()
- .stream()
+ return component.getCapabilities() != null && component.getComponentInstances() != null && component.getComponentInstances().stream()
.anyMatch(ci -> MapUtils.isNotEmpty(ci.getCapabilities()));
}
private static boolean groupsCapabilitiesExist(Component component) {
- return component.getCapabilities() != null && component.getGroups() != null
- && component.getGroups()
- .stream()
+ return component.getCapabilities() != null && component.getGroups() != null && component.getGroups().stream()
.anyMatch(g -> MapUtils.isNotEmpty(g.getCapabilities()));
}
public static MapCapabilityProperty convertToMapOfMapCapabilityProperties(Map<String, List<CapabilityDefinition>> capabilities, String ownerId,
boolean isAtomicType) {
-
Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>();
if (MapUtils.isNotEmpty(capabilities)) {
capabilities.forEach((s, caps) -> addCapsProperties(ownerId, isAtomicType, toscaCapPropMap, caps));
@@ -687,10 +605,8 @@ public class ModelConverter {
private static void addCapProperties(String ownerId, boolean isAtomicType, Map<String, MapPropertiesDataDefinition> toscaCapPropMap,
CapabilityDefinition cap) {
if (CollectionUtils.isNotEmpty(cap.getProperties())) {
- MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(cap.getProperties()
- .stream()
- .map(PropertyDataDefinition::new)
- .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)));
+ MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(
+ cap.getProperties().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)));
toscaCapPropMap.put(buildCapabilityPropertyKey(isAtomicType, cap.getType(), cap.getName(), ownerId, cap),
new MapPropertiesDataDefinition(dataToCreate));
}
@@ -699,16 +615,11 @@ public class ModelConverter {
public static String buildCapabilityPropertyKey(boolean isAtomicType, String capabilityType, String capabilityName,
String componentInstanceUniqueId, CapabilityDefinition cap) {
StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
- sb.append(CAP_PROP_DELIM)
- .append(cap.getOwnerId())
- .append(CAP_PROP_DELIM);
+ sb.append(CAP_PROP_DELIM).append(cap.getOwnerId()).append(CAP_PROP_DELIM);
if (!isAtomicType && !componentInstanceUniqueId.equals(cap.getOwnerId())) {
- sb.append(cap.getOwnerId())
- .append(CAP_PROP_DELIM);
+ sb.append(cap.getOwnerId()).append(CAP_PROP_DELIM);
}
- return sb.append(capabilityType)
- .append(CAP_PROP_DELIM)
- .append(capabilityName).toString();
+ return sb.append(capabilityType).append(CAP_PROP_DELIM).append(capabilityName).toString();
}
public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map<String, List<CapabilityDefinition>> instCapabilities,
@@ -718,57 +629,49 @@ public class ModelConverter {
public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map<String, List<CapabilityDefinition>> capabilities, String ownerId,
boolean fromCsar) {
-
Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>();
if (MapUtils.isNotEmpty(capabilities)) {
capabilities.forEach((s, caps) -> {
+ if (caps != null && !caps.isEmpty()) {
+ MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition();
+ for (CapabilityDefinition cap : caps) {
+ List<ComponentInstanceProperty> capPrps = cap.getProperties();
+ if (capPrps != null) {
+ for (ComponentInstanceProperty cip : capPrps) {
+ dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip));
+ }
+ // format key of capability properties :
+
+ // VF instance in service : instanceId#ownerId#type#capName
- if (caps != null && !caps.isEmpty()) {
-
- MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition();
-
- for (CapabilityDefinition cap : caps) {
- List<ComponentInstanceProperty> capPrps = cap.getProperties();
- if (capPrps != null) {
-
- for (ComponentInstanceProperty cip : capPrps) {
- dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip));
- }
- // format key of capability properties :
- // VF instance in service : instanceId#ownerId#type#capName
- // VFC instance ion VF : instanceId#ownerId#type#capName -> instanceId=ownerId
-
- StringBuilder sb = new StringBuilder(ownerId);
- sb.append(CAP_PROP_DELIM);
- if (fromCsar) {
- sb.append(ownerId);
- } else {
- sb.append(cap.getOwnerId());
- }
- sb.append(CAP_PROP_DELIM).append(s).append(CAP_PROP_DELIM).append(cap.getName());
- toscaCapPropMap.put(sb.toString(), new MapPropertiesDataDefinition(dataToCreate));
+ // VFC instance ion VF : instanceId#ownerId#type#capName -> instanceId=ownerId
+ StringBuilder sb = new StringBuilder(ownerId);
+ sb.append(CAP_PROP_DELIM);
+ if (fromCsar) {
+ sb.append(ownerId);
+ } else {
+ sb.append(cap.getOwnerId());
}
+ sb.append(CAP_PROP_DELIM).append(s).append(CAP_PROP_DELIM).append(cap.getName());
+ toscaCapPropMap.put(sb.toString(), new MapPropertiesDataDefinition(dataToCreate));
}
}
}
- );
+ });
}
return new MapCapabilityProperty(toscaCapPropMap);
}
private static MapListCapabilityDataDefinition convertToMapListCapabiltyDataDefinition(Map<String, List<CapabilityDefinition>> instCapabilities) {
-
Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
for (Entry<String, List<CapabilityDefinition>> instCapability : instCapabilities.entrySet()) {
mapToscaDataDefinition.put(instCapability.getKey(),
new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
}
-
return new MapListCapabilityDataDefinition(mapToscaDataDefinition);
}
private static void convertRequirements(Component component, TopologyTemplate topologyTemplate) {
-
convertTopologyTemplateRequirements(component, topologyTemplate);
if (component.getRequirements() != null && component.getComponentInstances() != null) {
topologyTemplate.setCalculatedRequirements(new HashMap<>());
@@ -787,13 +690,11 @@ public class ModelConverter {
private static MapListRequirementDataDefinition convertToMapListRequirementDataDefinition(
Map<String, List<RequirementDefinition>> instRequirements) {
-
Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
for (Entry<String, List<RequirementDefinition>> instRequirement : instRequirements.entrySet()) {
mapToscaDataDefinition.put(instRequirement.getKey(), new ListRequirementDataDefinition(
instRequirement.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
}
-
return new MapListRequirementDataDefinition(mapToscaDataDefinition);
}
@@ -810,7 +711,6 @@ public class ModelConverter {
component.setLastUpdaterFullName(toscaElement.getLastUpdaterFullName());
component.setLastUpdaterUserId(toscaElement.getLastUpdaterUserId());
component.setNormalizedName(toscaElement.getNormalizedName());
-
component.setLifecycleState(toscaElement.getLifecycleState());
component.setVersion(toscaElement.getVersion());
component.setHighestVersion(toscaElement.isHighestVersion());
@@ -818,19 +718,15 @@ public class ModelConverter {
component.setSystemName((String) toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME));
component.setDerivedFromGenericType(toscaElement.getDerivedFromGenericType());
component.setDerivedFromGenericVersion(toscaElement.getDerivedFromGenericVersion());
-
Map<String, PropertyDataDefinition> properties = toscaElement.getProperties();
if (MapUtils.isNotEmpty(properties)) {
List<PropertyDefinition> propertiesMap = properties.values().stream().map(x -> new PropertyDefinition(x)).collect(Collectors.toList());
component.setProperties(propertiesMap);
}
-
//archive
component.setArchived(toscaElement.isArchived() == null ? false : toscaElement.isArchived());
-
component.setArchiveTime(toscaElement.getArchiveTime());
component.setVspArchived(toscaElement.isVspArchived() == null ? false : toscaElement.isVspArchived());
-
if (component.getComponentType() == ComponentTypeEnum.RESOURCE) {
Resource resource = (Resource) component;
resource.setAbstract((Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT));
@@ -843,7 +739,6 @@ public class ModelConverter {
} else {
resource.setResourceVendorModelNumber("");
}
-
} else if (component.getComponentType() == ComponentTypeEnum.SERVICE) {
Service service = (Service) component;
if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)) != null) {
@@ -920,8 +815,8 @@ public class ModelConverter {
}
final List<DataTypeDefinition> dataTypes = resource.getDataTypes();
if (CollectionUtils.isNotEmpty(dataTypes)) {
- nodeType.setDataTypes(dataTypes.stream()
- .collect(Collectors.toMap(DataTypeDefinition::getName, dataTypeDefinition -> dataTypeDefinition)));
+ nodeType
+ .setDataTypes(dataTypes.stream().collect(Collectors.toMap(DataTypeDefinition::getName, dataTypeDefinition -> dataTypeDefinition)));
}
convertCommonToscaData(component, nodeType);
convertAdditionalInformation(component, nodeType);
@@ -975,48 +870,39 @@ public class ModelConverter {
Map<String, ArtifactDefinition> copy;
if (artifacts != null) {
copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue())));
-
} else {
copy = new HashMap<>();
}
component.setArtifacts(copy);
-
Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts();
if (toscaArtifacts != null) {
copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue())));
-
} else {
copy = new HashMap<>();
}
component.setToscaArtifacts(copy);
-
Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts();
if (deploymentArtifacts != null) {
copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue())));
-
} else {
copy = new HashMap<>();
}
component.setDeploymentArtifacts(copy);
}
- private static void convertNodeFiltersComponents(final TopologyTemplate topologyTemplate,
- final Component component) {
+ private static void convertNodeFiltersComponents(final TopologyTemplate topologyTemplate, final Component component) {
final Map<String, CINodeFilterDataDefinition> filters = topologyTemplate.getNodeFilterComponents();
final Map<String, CINodeFilterDataDefinition> copy;
if (MapUtils.isNotEmpty(filters)) {
- copy = filters.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> new CINodeFilterDataDefinition(e.getValue())));
+ copy = filters.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new CINodeFilterDataDefinition(e.getValue())));
} else {
copy = new HashMap<>();
}
component.setNodeFilterComponents(copy);
}
- private static void convertSubstitutionFiltersComponents(final TopologyTemplate topologyTemplate,
- final Component component) {
- final Map<String, SubstitutionFilterDataDefinition> filters = topologyTemplate
- .getSubstitutionFilterDataDefinitionMap();
+ private static void convertSubstitutionFiltersComponents(final TopologyTemplate topologyTemplate, final Component component) {
+ final Map<String, SubstitutionFilterDataDefinition> filters = topologyTemplate.getSubstitutionFilterDataDefinitionMap();
if (MapUtils.isNotEmpty(filters)) {
component.setSubstitutionFilter(filters.get(component.getUniqueId()));
}
@@ -1027,7 +913,6 @@ public class ModelConverter {
Map<String, ArtifactDefinition> copy;
if (serviceApiArtifacts != null) {
copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue())));
-
} else {
copy = new HashMap<>();
}
@@ -1039,7 +924,6 @@ public class ModelConverter {
Map<String, ForwardingPathDataDefinition> copy;
if (servicePaths != null) {
copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue())));
-
} else {
copy = new HashMap<>();
}
@@ -1053,14 +937,12 @@ public class ModelConverter {
.collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
toscaElement.setArtifacts(copy);
}
-
Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
if (toscaArtifacts != null) {
Map<String, ArtifactDataDefinition> copy = toscaArtifacts.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
toscaElement.setToscaArtifacts(copy);
}
-
Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
if (deploymentArtifacts != null) {
Map<String, ArtifactDataDefinition> copy = deploymentArtifacts.entrySet().stream()
@@ -1080,21 +962,15 @@ public class ModelConverter {
private static void convertCapabilities(Component component, NodeType toscaElement) {
Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
-
Map<String, ListCapabilityDataDefinition> toscaCapMap = new HashMap<>();
Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>();
-
if (capabilities != null && !capabilities.isEmpty()) {
capabilities.forEach((s, caps) -> {
-
- if (caps != null && !caps.isEmpty()) {
- List<CapabilityDataDefinition> capList = caps.stream().map(CapabilityDataDefinition::new).collect(Collectors.toList());
-
- populateCapabilityMap(toscaCapMap, toscaCapPropMap, s, caps, capList);
- }
+ if (caps != null && !caps.isEmpty()) {
+ List<CapabilityDataDefinition> capList = caps.stream().map(CapabilityDataDefinition::new).collect(Collectors.toList());
+ populateCapabilityMap(toscaCapMap, toscaCapPropMap, s, caps, capList);
}
- );
-
+ });
toscaElement.setCapabilities(toscaCapMap);
toscaElement.setCapabilitiesProperties(toscaCapPropMap);
}
@@ -1111,20 +987,15 @@ public class ModelConverter {
private static void convertRequirements(Resource component, NodeType nodeType) {
Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
-
Map<String, ListRequirementDataDefinition> toscaReqMap = new HashMap<>();
-
if (requirements != null && !requirements.isEmpty()) {
requirements.forEach((s, reqs) -> {
-
- if (reqs != null && !reqs.isEmpty()) {
- List<RequirementDataDefinition> reqList = reqs.stream().map(RequirementDataDefinition::new).collect(Collectors.toList());
-
- ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList);
- toscaReqMap.put(s, listRequirementDataDefinition);
- }
+ if (reqs != null && !reqs.isEmpty()) {
+ List<RequirementDataDefinition> reqList = reqs.stream().map(RequirementDataDefinition::new).collect(Collectors.toList());
+ ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList);
+ toscaReqMap.put(s, listRequirementDataDefinition);
}
- );
+ });
nodeType.setRequirements(toscaReqMap);
}
}
@@ -1132,7 +1003,6 @@ public class ModelConverter {
private static void convertCapabilities(NodeType toscaElement, Component component) {
Map<String, ListCapabilityDataDefinition> toscaCapabilities = toscaElement.getCapabilities();
Map<String, MapPropertiesDataDefinition> toscaCapPropMap = toscaElement.getCapabilitiesProperties();
-
Map<String, List<CapabilityDefinition>> capabilitiesMapFromMapObject = getCapabilitiesMapFromMapObject(toscaCapabilities, toscaCapPropMap);
if (capabilitiesMapFromMapObject != null) {
component.setCapabilities(capabilitiesMapFromMapObject);
@@ -1146,35 +1016,28 @@ public class ModelConverter {
return null;
}
toscaCapabilities.forEach((s, cap) -> {
-
- if (cap != null) {
- List<CapabilityDataDefinition> capDataList = cap.getListToscaDataDefinition();
-
- if (capDataList != null && !capDataList.isEmpty()) {
- List<CapabilityDefinition> capList = capDataList.stream().map(CapabilityDefinition::new).collect(Collectors.toList());
- compCap.put(s, capList);
- }
+ if (cap != null) {
+ List<CapabilityDataDefinition> capDataList = cap.getListToscaDataDefinition();
+ if (capDataList != null && !capDataList.isEmpty()) {
+ List<CapabilityDefinition> capList = capDataList.stream().map(CapabilityDefinition::new).collect(Collectors.toList());
+ compCap.put(s, capList);
}
-
}
- );
+ });
if (toscaCapPropMap != null && !toscaCapPropMap.isEmpty()) {
toscaCapPropMap.forEach((s, capProp) -> {
- String[] result = s.split(CAP_PROP_DELIM);
- if (capProp != null) {
- Map<String, PropertyDataDefinition> capMap = capProp.getMapToscaDataDefinition();
-
- if (capMap != null && !capMap.isEmpty()) {
- List<ComponentInstanceProperty> capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new)
- .collect(Collectors.toList());
-
- List<CapabilityDefinition> cap = compCap.get(result[0]);
- Optional<CapabilityDefinition> op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst();
- op.ifPresent(capabilityDefinition -> capabilityDefinition.setProperties(capPropsList));
- }
+ String[] result = s.split(CAP_PROP_DELIM);
+ if (capProp != null) {
+ Map<String, PropertyDataDefinition> capMap = capProp.getMapToscaDataDefinition();
+ if (capMap != null && !capMap.isEmpty()) {
+ List<ComponentInstanceProperty> capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new)
+ .collect(Collectors.toList());
+ List<CapabilityDefinition> cap = compCap.get(result[0]);
+ Optional<CapabilityDefinition> op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst();
+ op.ifPresent(capabilityDefinition -> capabilityDefinition.setProperties(capPropsList));
}
}
- );
+ });
}
return compCap;
}
@@ -1201,7 +1064,6 @@ public class ModelConverter {
private static void convertGroups(Component component, TopologyTemplate toscaElement) {
List<GroupDefinition> groupDefinitions = component.getGroups();
Map<String, GroupDataDefinition> groups = new HashMap<>();
-
if (groupDefinitions != null && groups.isEmpty()) {
groups = groupDefinitions.stream().collect(Collectors.toMap(GroupDefinition::getInvariantName, GroupDefinition::new));
}
@@ -1219,23 +1081,19 @@ public class ModelConverter {
private static void convertRequirements(NodeType toscaElement, Component component) {
Map<String, ListRequirementDataDefinition> toscaRequirements = toscaElement.getRequirements();
-
Map<String, List<RequirementDefinition>> compReqs = new HashMap<>();
if (toscaRequirements == null || toscaRequirements.isEmpty()) {
return;
}
toscaRequirements.forEach((s, req) -> {
-
- if (req != null) {
- List<RequirementDataDefinition> reqDataList = req.getListToscaDataDefinition();
-
- if (reqDataList != null && !reqDataList.isEmpty()) {
- List<RequirementDefinition> reqList = reqDataList.stream().map(RequirementDefinition::new).collect(Collectors.toList());
- compReqs.put(s, reqList);
- }
+ if (req != null) {
+ List<RequirementDataDefinition> reqDataList = req.getListToscaDataDefinition();
+ if (reqDataList != null && !reqDataList.isEmpty()) {
+ List<RequirementDefinition> reqList = reqDataList.stream().map(RequirementDefinition::new).collect(Collectors.toList());
+ compReqs.put(s, reqList);
}
}
- );
+ });
component.setRequirements(compReqs);
}
@@ -1243,7 +1101,6 @@ public class ModelConverter {
TopologyTemplate topologyTemplate;
ComponentTypeEnum componentType = component.getComponentType();
topologyTemplate = new TopologyTemplate();
-
if (componentType == ComponentTypeEnum.RESOURCE) {
Resource resource = (Resource) component;
topologyTemplate.setResourceType(resource.getResourceType());
@@ -1257,10 +1114,8 @@ public class ModelConverter {
}
convertCommonToscaData(component, topologyTemplate);
convertArtifacts(component, topologyTemplate);
-
convertAdditionalInformation(component, topologyTemplate);
convertComponentInstances(component, topologyTemplate);
-
convertInputs(component, topologyTemplate);
convertProperties(component, topologyTemplate);
convertAttributesToTopologyTemplate(component, topologyTemplate);
@@ -1269,7 +1124,6 @@ public class ModelConverter {
convertPolicies(component, topologyTemplate);
convertRequirements(component, topologyTemplate);
convertRelationsToComposition(component, topologyTemplate);
-
return topologyTemplate;
}
@@ -1300,16 +1154,13 @@ public class ModelConverter {
private static void convertServiceMetaData(Service service, TopologyTemplate topologyTemplate) {
if (service.getDistributionStatus() != null) {
- topologyTemplate.setMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS,
- service.getDistributionStatus().name());
+ topologyTemplate.setMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS, service.getDistributionStatus().name());
}
topologyTemplate.setMetadataValue(JsonPresentationFields.PROJECT_CODE, service.getProjectCode());
- topologyTemplate.setMetadataValue(JsonPresentationFields.ECOMP_GENERATED_NAMING,
- service.isEcompGeneratedNaming());
+ topologyTemplate.setMetadataValue(JsonPresentationFields.ECOMP_GENERATED_NAMING, service.isEcompGeneratedNaming());
topologyTemplate.setMetadataValue(JsonPresentationFields.NAMING_POLICY, service.getNamingPolicy());
topologyTemplate.setMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT, service.getEnvironmentContext());
topologyTemplate.setMetadataValue(JsonPresentationFields.INSTANTIATION_TYPE, service.getInstantiationType());
-
}
private static void convertRelationsToComposition(Component component, TopologyTemplate topologyTemplate) {
@@ -1324,7 +1175,6 @@ public class ModelConverter {
compositionDataDefinition = new CompositionDataDefinition();
compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), compositionDataDefinition);
}
-
Map<String, RelationshipInstDataDefinition> relations = componentInstancesRelations.stream()
.flatMap(x -> convertRelationToToscaRelation(x).stream()).filter(i -> i.getUniqueId() != null)
.collect(Collectors.toMap(RelationshipInstDataDefinition::getUniqueId, Function.identity()));
@@ -1335,21 +1185,16 @@ public class ModelConverter {
private static void convertInputs(Component component, TopologyTemplate topologyTemplate) {
List<InputDefinition> inputsList = component.getInputs();
if (inputsList != null && !inputsList.isEmpty()) {
-
Map<String, PropertyDataDefinition> inputsMap = inputsList.stream().map(PropertyDataDefinition::new)
.collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()));
topologyTemplate.setInputs(inputsMap);
}
-
}
private static void convertInputs(TopologyTemplate topologyTemplate, Component component) {
Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();
if (inputsMap != null && !inputsMap.isEmpty()) {
- List<InputDefinition> inputsList = inputsMap.values()
- .stream()
- .map(InputDefinition::new)
- .collect(Collectors.toList());
+ List<InputDefinition> inputsList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
component.setInputs(inputsList);
}
}
@@ -1359,18 +1204,15 @@ public class ModelConverter {
if (MapUtils.isEmpty(outputsMap)) {
return;
}
- final List<OutputDefinition> outputList = outputsMap.values()
- .stream()
- .map(OutputDefinition::new)
- .collect(Collectors.toList());
+ final List<OutputDefinition> outputList = outputsMap.values().stream().map(OutputDefinition::new).collect(Collectors.toList());
component.setOutputs(outputList);
}
private static void convertProperties(Component component, TopologyTemplate topologyTemplate) {
List<PropertyDefinition> propertiesList = component.getProperties();
if (propertiesList != null && !propertiesList.isEmpty()) {
- Map<String, PropertyDataDefinition> propertiesMap = propertiesList.stream()
- .map(i -> new PropertyDataDefinition(i)).collect(Collectors.toMap(i -> i.getName(), i -> i));
+ Map<String, PropertyDataDefinition> propertiesMap = propertiesList.stream().map(i -> new PropertyDataDefinition(i))
+ .collect(Collectors.toMap(i -> i.getName(), i -> i));
topologyTemplate.setProperties(propertiesMap);
}
}
@@ -1378,8 +1220,8 @@ public class ModelConverter {
private static void convertAttributesToTopologyTemplate(final Component component, final TopologyTemplate topologyTemplate) {
final List<AttributeDefinition> attributes = component.getAttributes();
if (CollectionUtils.isNotEmpty(attributes)) {
- final Map<String, AttributeDataDefinition> attributeDataDefinitionMap = attributes.stream()
- .map(AttributeDataDefinition::new).collect(Collectors.toMap(AttributeDataDefinition::getName, i -> i));
+ final Map<String, AttributeDataDefinition> attributeDataDefinitionMap = attributes.stream().map(AttributeDataDefinition::new)
+ .collect(Collectors.toMap(AttributeDataDefinition::getName, i -> i));
topologyTemplate.setAttributes(attributeDataDefinitionMap);
}
}
@@ -1388,8 +1230,7 @@ public class ModelConverter {
Map<String, PropertyDataDefinition> propertiesMap = topologyTemplate.getProperties();
if (propertiesMap != null && !propertiesMap.isEmpty()) {
Map<String, PropertyDefinition> copy = propertiesMap.entrySet().stream()
- .collect(Collectors.toMap(entry -> entry.getKey(), entry -> new PropertyDefinition
- (entry.getValue())));
+ .collect(Collectors.toMap(entry -> entry.getKey(), entry -> new PropertyDefinition(entry.getValue())));
component.setProperties(new ArrayList<>(copy.values()));
}
}
@@ -1406,20 +1247,18 @@ public class ModelConverter {
private static void convertDataTypes(final ToscaElement toscaElement, final Component component) {
final Map<String, DataTypeDataDefinition> dataTypeDataMap = toscaElement.getDataTypes();
if (MapUtils.isNotEmpty(dataTypeDataMap)) {
- final List<DataTypeDefinition> dataTypeDefinitionList =
- dataTypeDataMap.values().stream().map(dataTypeDataDefinition -> {
- final DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(dataTypeDataDefinition);
-
- if (CollectionUtils.isNotEmpty(dataTypeDataDefinition.getPropertiesData())) {
- log.debug("#convertDataTypes - propertiesData is not null. {}",
- ReflectionToStringBuilder.toString(dataTypeDataDefinition.getPropertiesData()));
- dataTypeDefinition.setProperties(dataTypeDataDefinition.getPropertiesData().stream()
- .map(PropertyDefinition::new).collect(Collectors.toList()));
- } else {
- log.debug("#convertDataTypes - propertiesData is null. ignore.");
- }
- return dataTypeDefinition;
- }).collect(Collectors.toList());
+ final List<DataTypeDefinition> dataTypeDefinitionList = dataTypeDataMap.values().stream().map(dataTypeDataDefinition -> {
+ final DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(dataTypeDataDefinition);
+ if (CollectionUtils.isNotEmpty(dataTypeDataDefinition.getPropertiesData())) {
+ log.debug("#convertDataTypes - propertiesData is not null. {}",
+ ReflectionToStringBuilder.toString(dataTypeDataDefinition.getPropertiesData()));
+ dataTypeDefinition
+ .setProperties(dataTypeDataDefinition.getPropertiesData().stream().map(PropertyDefinition::new).collect(Collectors.toList()));
+ } else {
+ log.debug("#convertDataTypes - propertiesData is null. ignore.");
+ }
+ return dataTypeDefinition;
+ }).collect(Collectors.toList());
component.setDataTypes(dataTypeDefinitionList);
}
}
@@ -1442,12 +1281,10 @@ public class ModelConverter {
toscaElement.setLastUpdaterUserId(component.getLastUpdaterUserId());
toscaElement.setDerivedFromGenericType(component.getDerivedFromGenericType());
toscaElement.setDerivedFromGenericVersion(component.getDerivedFromGenericVersion());
-
//Archive
toscaElement.setArchived(component.isArchived() == null ? false : component.isArchived());
toscaElement.setArchiveTime(component.getArchiveTime() == null ? 0L : component.getArchiveTime());
toscaElement.setVspArchived(component.isVspArchived() == null ? false : component.isVspArchived());
-
toscaElement.setLifecycleState(component.getLifecycleState());
toscaElement.setMetadataValue(JsonPresentationFields.VERSION, component.getVersion());
if (component.getComponentType() == ComponentTypeEnum.RESOURCE) {
@@ -1490,20 +1327,17 @@ public class ModelConverter {
for (final String key : component.getCategorySpecificMetadata().keySet()) {
toscaElement.setMetadataValue(key, component.getCategorySpecificMetadata().get(key));
}
-
final List<DataTypeDefinition> dataTypes = component.getDataTypes();
if (CollectionUtils.isNotEmpty(dataTypes)) {
- toscaElement.setDataTypes(dataTypes.stream()
- .collect(Collectors.toMap(DataTypeDefinition::getName, dataTypeDefinition -> dataTypeDefinition)));
+ toscaElement
+ .setDataTypes(dataTypes.stream().collect(Collectors.toMap(DataTypeDefinition::getName, dataTypeDefinition -> dataTypeDefinition)));
}
}
private static void setComponentInstancesToComponent(TopologyTemplate topologyTemplate, Component component) {
-
List<ComponentInstance> componentInstances = new ArrayList<>();
ComponentInstance currComponentInstance;
Map<String, CINodeFilterDataDefinition> nodeFilterComponents = topologyTemplate.getNodeFilterComponents();
-
for (Map.Entry<String, ComponentInstanceDataDefinition> entry : topologyTemplate.getComponentInstances().entrySet()) {
String key = entry.getKey();
currComponentInstance = new ComponentInstance(topologyTemplate.getComponentInstances().get(key));
@@ -1531,8 +1365,7 @@ public class ModelConverter {
final Map<String, MapAttributesDataDefinition> instAttributes = topologyTemplate.getInstAttributes();
if (instAttributes != null && instAttributes.containsKey(key) && instAttributes.get(key) != null) {
currComponentInstance.setAttributes(
- instAttributes.get(key).getMapToscaDataDefinition().values().stream().map(AttributeDefinition::new)
- .collect(Collectors.toList()));
+ instAttributes.get(key).getMapToscaDataDefinition().values().stream().map(AttributeDefinition::new).collect(Collectors.toList()));
}
if (topologyTemplate.getComponentInstInterfaces() != null && topologyTemplate.getComponentInstInterfaces().containsKey(key)
&& topologyTemplate.getComponentInstInterfaces().get(key) != null) {
@@ -1541,7 +1374,6 @@ public class ModelConverter {
currComponentInstance.setInterfaces(interfacesMap);
}
componentInstances.add(currComponentInstance);
-
}
component.setComponentInstances(componentInstances);
}
@@ -1613,10 +1445,8 @@ public class ModelConverter {
for (Entry<String, MapPropertiesDataDefinition> entry : topologyTemplate.getInstProperties().entrySet()) {
if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) {
String key = entry.getKey();
- List<ComponentInstanceProperty> componentInstanceAttributes = entry.getValue()
- .getMapToscaDataDefinition().entrySet().stream()
- .map(e -> new ComponentInstanceProperty(new PropertyDefinition(e.getValue())))
- .collect(Collectors.toList());
+ List<ComponentInstanceProperty> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream()
+ .map(e -> new ComponentInstanceProperty(new PropertyDefinition(e.getValue()))).collect(Collectors.toList());
properties.put(key, componentInstanceAttributes);
}
}
@@ -1630,10 +1460,8 @@ public class ModelConverter {
for (Map.Entry<String, MapAttributesDataDefinition> entry : mapAttributesDataDefinitionMap.entrySet()) {
if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) {
String key = entry.getKey();
- List<ComponentInstanceAttribute> componentInstanceAttributes = entry.getValue()
- .getMapToscaDataDefinition().entrySet().stream()
- .map(e -> new ComponentInstanceAttribute(new AttributeDefinition(e.getValue())))
- .collect(Collectors.toList());
+ List<ComponentInstanceAttribute> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream()
+ .map(e -> new ComponentInstanceAttribute(new AttributeDefinition(e.getValue()))).collect(Collectors.toList());
attributes.put(key, componentInstanceAttributes);
}
}
@@ -1646,10 +1474,8 @@ public class ModelConverter {
for (Map.Entry<String, MapInterfaceInstanceDataDefinition> entry : topologyTemplate.getInstInterfaces().entrySet()) {
if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) {
String key = entry.getKey();
- List<ComponentInstanceInterface> componentInstanceInterfaces = entry.getValue()
- .getMapToscaDataDefinition().entrySet().stream().map(e -> new
- ComponentInstanceInterface(e.getKey(), e.getValue()))
- .collect(Collectors.toList());
+ List<ComponentInstanceInterface> componentInstanceInterfaces = entry.getValue().getMapToscaDataDefinition().entrySet().stream()
+ .map(e -> new ComponentInstanceInterface(e.getKey(), e.getValue())).collect(Collectors.toList());
interfaces.put(key, componentInstanceInterfaces);
}
}
@@ -1659,29 +1485,23 @@ public class ModelConverter {
for (Map.Entry<String, MapInterfaceDataDefinition> entry : topologyTemplate.getComponentInstInterfaces().entrySet()) {
if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) {
String key = entry.getKey();
- List<ComponentInstanceInterface> componentInstanceInterfaces = entry.getValue()
- .getMapToscaDataDefinition().entrySet().stream().map(e -> new
- ComponentInstanceInterface(e.getKey(), e.getValue()))
- .collect(Collectors.toList());
+ List<ComponentInstanceInterface> componentInstanceInterfaces = entry.getValue().getMapToscaDataDefinition().entrySet().stream()
+ .map(e -> new ComponentInstanceInterface(e.getKey(), e.getValue())).collect(Collectors.toList());
interfaces.put(key, componentInstanceInterfaces);
}
}
component.setComponentInstancesInterfaces(interfaces);
}
-
}
private static void setComponentInstancesAttributesToComponent(TopologyTemplate topologyTemplate, Component component) {
if (topologyTemplate.getInstAttributes() != null) {
Map<String, List<ComponentInstanceAttribute>> attributes = new HashMap<>();
- for (Map.Entry<String, MapAttributesDataDefinition> entry : topologyTemplate.getInstAttributes()
- .entrySet()) {
+ for (Map.Entry<String, MapAttributesDataDefinition> entry : topologyTemplate.getInstAttributes().entrySet()) {
if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) {
String key = entry.getKey();
- List<ComponentInstanceAttribute> componentInstanceAttributes = entry.getValue()
- .getMapToscaDataDefinition().entrySet().stream()
- .map(e -> new ComponentInstanceAttribute(new AttributeDefinition(e.getValue())))
- .collect(Collectors.toList());
+ List<ComponentInstanceAttribute> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream()
+ .map(e -> new ComponentInstanceAttribute(new AttributeDefinition(e.getValue()))).collect(Collectors.toList());
attributes.put(key, componentInstanceAttributes);
}
}
@@ -1689,9 +1509,7 @@ public class ModelConverter {
}
}
-
public static void setComponentInstancesRequirementsToComponent(TopologyTemplate topologyTemplate, Component component) {
-
if (topologyTemplate.getCalculatedRequirements() != null) {
// Requirements of component organized by capability
Map<String, List<RequirementDefinition>> instanceRequiermentsFromMapObject = getInstanceRequirementsFromMapObject(
@@ -1710,11 +1528,9 @@ public class ModelConverter {
instancesMap.put(currInstance.getUniqueId(), currInstance);
}
for (Map.Entry<String, MapListRequirementDataDefinition> entry : mapListRequirements.entrySet()) {
-
String instanceId = entry.getKey();
// Requirements of instance organized by capability
Map<String, ListRequirementDataDefinition> capsMapList = entry.getValue().getMapToscaDataDefinition();
-
if (capsMapList != null) {
for (Entry<String, ListRequirementDataDefinition> entryTypeList : capsMapList.entrySet()) {
String capabilityType = entryTypeList.getKey();
@@ -1739,21 +1555,17 @@ public class ModelConverter {
public static void setComponentInstancesCapabilitiesToComponentAndCI(TopologyTemplate topologyTemplate, Component component) {
Map<String, MapCapabilityProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties();
-
if (topologyTemplate.getCalculatedCapabilities() != null) {
// capabilities of component organized by type
Map<String, List<CapabilityDefinition>> instancesCapabilities = new HashMap<>();
-
Map<String, ComponentInstance> instancesMap = new HashMap<>();
for (ComponentInstance currInstance : component.getComponentInstances()) {
instancesMap.put(currInstance.getUniqueId(), currInstance);
}
for (Map.Entry<String, MapListCapabilityDataDefinition> entry : topologyTemplate.getCalculatedCapabilities().entrySet()) {
-
String instanceId = entry.getKey();
// capabilities of instance organized by type
Map<String, ListCapabilityDataDefinition> capsMapList = entry.getValue().getMapToscaDataDefinition();
-
if (capsMapList != null) {
for (Entry<String, ListCapabilityDataDefinition> entryTypeList : capsMapList.entrySet()) {
String capabilityType = entryTypeList.getKey();
@@ -1785,31 +1597,25 @@ public class ModelConverter {
Map<String, ListCapabilityDataDefinition> capabilities = topologyTemplate.getCapabilities();
Map<String, MapPropertiesDataDefinition> capabilitiesProperties = topologyTemplate.getCapabilitiesProperties();
Map<String, List<CapabilityDefinition>> allCapabilities = new HashMap<>();
-
if (MapUtils.isNotEmpty(capabilities)) {
allCapabilities.putAll(groupCapabilityByType(capabilities));
}
-
if (MapUtils.isNotEmpty(capabilitiesProperties)) {
capabilitiesProperties.forEach((s, capProp) -> {
- String[] result = s.split(CAP_PROP_DELIM);
- if (capProp != null) {
- Map<String, PropertyDataDefinition> capMap = capProp.getMapToscaDataDefinition();
-
- if (MapUtils.isNotEmpty(capMap)) {
- List<ComponentInstanceProperty> capPropsList = capMap.values().stream()
- .map(ComponentInstanceProperty::new).collect(Collectors.toList());
-
- List<CapabilityDefinition> cap = allCapabilities.get(result[0]);
- if (cap != null) {
- Optional<CapabilityDefinition> op = cap.stream().filter(c -> c.getName()
- .equals(result[1])).findFirst();
- op.ifPresent(capabilityDefinition -> capabilityDefinition.setProperties(capPropsList));
- }
+ String[] result = s.split(CAP_PROP_DELIM);
+ if (capProp != null) {
+ Map<String, PropertyDataDefinition> capMap = capProp.getMapToscaDataDefinition();
+ if (MapUtils.isNotEmpty(capMap)) {
+ List<ComponentInstanceProperty> capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new)
+ .collect(Collectors.toList());
+ List<CapabilityDefinition> cap = allCapabilities.get(result[0]);
+ if (cap != null) {
+ Optional<CapabilityDefinition> op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst();
+ op.ifPresent(capabilityDefinition -> capabilityDefinition.setProperties(capPropsList));
}
}
}
- );
+ });
}
Map<String, List<CapabilityDefinition>> componentCapabilities = component.getCapabilities();
if (MapUtils.isNotEmpty(componentCapabilities)) {
@@ -1818,8 +1624,7 @@ public class ModelConverter {
component.setCapabilities(allCapabilities);
}
- private static void mergeCapabilityMap(Map<String, List<CapabilityDefinition>> map1,
- Map<String, List<CapabilityDefinition>> map2) {
+ private static void mergeCapabilityMap(Map<String, List<CapabilityDefinition>> map1, Map<String, List<CapabilityDefinition>> map2) {
map1.forEach((key1, val1) -> map2.forEach((key2, val2) -> {
if (key1.equals(key2)) {
val2.addAll(val1);
@@ -1828,24 +1633,20 @@ public class ModelConverter {
map1.putAll(map2);
}
- private static Map<String, List<CapabilityDefinition>> groupCapabilityByType(Map<String,
- ListCapabilityDataDefinition> capabilities) {
+ private static Map<String, List<CapabilityDefinition>> groupCapabilityByType(Map<String, ListCapabilityDataDefinition> capabilities) {
Map<String, List<CapabilityDefinition>> groupedCapabilities = new HashMap<>();
-
Set<String> typesSet = new HashSet<>();
List<CapabilityDefinition> allCapabilityDefinitions = new ArrayList<>();
for (Entry<String, ListCapabilityDataDefinition> capabilitiesEntry : capabilities.entrySet()) {
- typesSet.addAll(capabilitiesEntry.getValue().getListToscaDataDefinition()
- .stream().map(CapabilityDataDefinition::getType).collect(Collectors.toSet()));
-
- allCapabilityDefinitions.addAll(capabilitiesEntry.getValue().getListToscaDataDefinition()
- .stream().map(CapabilityDefinition::new).collect(Collectors.toList()));
+ typesSet.addAll(capabilitiesEntry.getValue().getListToscaDataDefinition().stream().map(CapabilityDataDefinition::getType)
+ .collect(Collectors.toSet()));
+ allCapabilityDefinitions.addAll(
+ capabilitiesEntry.getValue().getListToscaDataDefinition().stream().map(CapabilityDefinition::new).collect(Collectors.toList()));
}
-
for (String capType : typesSet) {
- groupedCapabilities.put(capType, allCapabilityDefinitions.stream()
- .filter(capabilityDefinition -> capabilityDefinition.getType()
- .equals(capType)).collect(Collectors.toList()));
+ groupedCapabilities.put(capType,
+ allCapabilityDefinitions.stream().filter(capabilityDefinition -> capabilityDefinition.getType().equals(capType))
+ .collect(Collectors.toList()));
}
return groupedCapabilities;
}
@@ -1862,36 +1663,29 @@ public class ModelConverter {
}
}
- private static Map<String, List<RequirementDefinition>> groupRequirementByType(Map<String,
- ListRequirementDataDefinition> requirements) {
+ private static Map<String, List<RequirementDefinition>> groupRequirementByType(Map<String, ListRequirementDataDefinition> requirements) {
Map<String, List<RequirementDefinition>> groupedRequirement = new HashMap<>();
-
Set<String> typesSet = new HashSet<>();
List<RequirementDefinition> allRequirements = new ArrayList<>();
for (Entry<String, ListRequirementDataDefinition> requirementsEntry : requirements.entrySet()) {
- typesSet.addAll(requirementsEntry.getValue().getListToscaDataDefinition()
- .stream().map(RequirementDataDefinition::getCapability).collect(Collectors.toSet()));
-
- allRequirements.addAll(requirementsEntry.getValue().getListToscaDataDefinition()
- .stream().map(RequirementDefinition::new).collect(Collectors.toList()));
+ typesSet.addAll(requirementsEntry.getValue().getListToscaDataDefinition().stream().map(RequirementDataDefinition::getCapability)
+ .collect(Collectors.toSet()));
+ allRequirements.addAll(
+ requirementsEntry.getValue().getListToscaDataDefinition().stream().map(RequirementDefinition::new).collect(Collectors.toList()));
}
-
for (String capType : typesSet) {
- groupedRequirement.put(capType, allRequirements.stream().filter(requirementDefinition ->
- requirementDefinition.getCapability().equals(capType)).collect(Collectors.toList()));
+ groupedRequirement.put(capType,
+ allRequirements.stream().filter(requirementDefinition -> requirementDefinition.getCapability().equals(capType))
+ .collect(Collectors.toList()));
}
return groupedRequirement;
-
}
private static void setCapabilitiesToComponentAndGroups(TopologyTemplate topologyTemplate, Component component) {
-
Map<String, MapCapabilityProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties();
-
if (capabilitiesAndGroupsExist(topologyTemplate, component)) {
Map<String, GroupDefinition> groupsMap = component.getGroups().stream()
.collect(Collectors.toMap(GroupDefinition::getUniqueId, Function.identity()));
-
for (Map.Entry<String, MapListCapabilityDataDefinition> entry : topologyTemplate.getCalculatedCapabilities().entrySet()) {
findSetCapabilitiesToComponentAndGroup(calculatedCapProperties, component, groupsMap, entry);
}
@@ -1905,7 +1699,6 @@ public class ModelConverter {
private static void findSetCapabilitiesToComponentAndGroup(Map<String, MapCapabilityProperty> calculatedCapProperties, Component component,
Map<String, GroupDefinition> groupsMap,
Map.Entry<String, MapListCapabilityDataDefinition> entry) {
-
String uniqueId = entry.getKey();
if (groupsMap.containsKey(uniqueId)) {
setCapabilitiesToComponentAndGroup(calculatedCapProperties, component, entry, groupsMap.get(uniqueId));
@@ -1916,7 +1709,6 @@ public class ModelConverter {
private static void setCapabilitiesToComponentAndGroup(Map<String, MapCapabilityProperty> calculatedCapProperties, Component component,
Map.Entry<String, MapListCapabilityDataDefinition> entry, GroupDefinition group) {
-
for (Entry<String, ListCapabilityDataDefinition> entryTypeList : entry.getValue().getMapToscaDataDefinition().entrySet()) {
String capabilityType = entryTypeList.getKey();
List<CapabilityDefinition> caps = entryTypeList.getValue().getListToscaDataDefinition().stream()
@@ -1946,9 +1738,13 @@ public class ModelConverter {
private static void findConvertSetProperties(CapabilityDataDefinition cap, String primaryPathKey, CapabilityDefinition capability, String path,
MapPropertiesDataDefinition capProp) {
// format key of capability properties :
+
// VF instance in service : instanceId#ownerId#type#capName
+
// VFC instance in VF : instanceId#type#capName -> instanceId=ownerId
+
// Group in service : groupName#ownerId#type#capName
+
// Group in VF : groupName#type#capName -> groupName=ownerId
String[] result = path.split(CAP_PROP_DELIM);
if (result.length < 4) {
@@ -1976,7 +1772,6 @@ public class ModelConverter {
}
private static void setComponentInstancesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) {
-
Map<String, ComponentInstanceDataDefinition> componentInstances = new HashMap<>();
ComponentInstanceDataDefinition convertedInstance;
if (component.getComponentInstances() != null) {
@@ -1984,7 +1779,6 @@ public class ModelConverter {
convertedInstance = new ComponentInstanceDataDefinition(instance);
if (instance.getGroupInstances() != null) {
MapGroupsDataDefinition groupsMap = new MapGroupsDataDefinition();
-
groupsMap.setMapToscaDataDefinition(instance.getGroupInstances().stream().map(GroupInstanceDataDefinition::new)
.collect(Collectors.toMap(GroupInstanceDataDefinition::getName, Function.identity())));
if (topologyTemplate.getInstGroups() == null) {
@@ -1996,48 +1790,39 @@ public class ModelConverter {
}
}
topologyTemplate.setComponentInstances(componentInstances);
-
}
private static void setComponentInstancesInputsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) {
-
if (component.getComponentInstancesInputs() != null) {
topologyTemplate.setInstInputs(new HashMap<>());
MapPropertiesDataDefinition inputsMap;
for (Entry<String, List<ComponentInstanceInput>> entry : component.getComponentInstancesInputs().entrySet()) {
inputsMap = new MapPropertiesDataDefinition();
-
inputsMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new)
.collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())));
-
topologyTemplate.getInstInputs().put(entry.getKey(), inputsMap);
}
}
}
private static void setComponentInstancesPropertiesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) {
-
if (component.getComponentInstancesProperties() != null) {
topologyTemplate.setInstProperties(new HashMap<>());
MapPropertiesDataDefinition propertiesMap;
for (Entry<String, List<ComponentInstanceProperty>> entry : component.getComponentInstancesProperties().entrySet()) {
propertiesMap = new MapPropertiesDataDefinition();
-
propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new)
.collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())));
-
topologyTemplate.getInstProperties().put(entry.getKey(), propertiesMap);
}
}
}
private static void setComponentInstancesArtifactsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) {
-
List<ComponentInstance> componentInstances = component.getComponentInstances();
if (componentInstances != null) {
topologyTemplate.setInstanceArtifacts(new HashMap<>());
topologyTemplate.setInstDeploymentArtifacts(new HashMap<>());
-
for (ComponentInstance ci : componentInstances) {
Map<String, ArtifactDefinition> artifacts = ci.getArtifacts();
if (artifacts != null) {
@@ -2046,7 +1831,6 @@ public class ModelConverter {
MapArtifactDataDefinition insArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionArtifact);
topologyTemplate.getInstanceArtifacts().put(ci.getUniqueId(), insArtifact);
}
-
Map<String, ArtifactDefinition> deplArtifacts = ci.getDeploymentArtifacts();
if (deplArtifacts != null) {
Map<String, ArtifactDataDefinition> mapToscaDataDefinitionDepArtifact = deplArtifacts.entrySet().stream()
@@ -2059,16 +1843,12 @@ public class ModelConverter {
}
private static void setComponentInstancesAttributesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) {
-
if (component.getComponentInstancesAttributes() != null) {
topologyTemplate.setInstAttributes(new HashMap<>());
-
for (Entry<String, List<ComponentInstanceAttribute>> entry : component.getComponentInstancesAttributes().entrySet()) {
final MapAttributesDataDefinition attributesMap = new MapAttributesDataDefinition();
-
attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(AttributeDefinition::new)
.collect(Collectors.toMap(AttributeDefinition::getName, Function.identity(), (entity1, entity2) -> entity1)));
-
topologyTemplate.getInstAttributes().put(entry.getKey(), attributesMap);
}
}
@@ -2119,7 +1899,6 @@ public class ModelConverter {
}
public static List<GroupDefinition> convertToGroupDefinitions(Map<String, GroupDataDefinition> groups) {
-
List<GroupDefinition> groupDefinitions = new ArrayList<>();
if (MapUtils.isNotEmpty(groups)) {
groupDefinitions = groups.values().stream().map(GroupDefinition::new).collect(Collectors.toList());
@@ -2128,18 +1907,14 @@ public class ModelConverter {
}
public static Map<String, MapCapabilityProperty> extractCapabilityProperteisFromInstances(List<ComponentInstance> instances, boolean fromCsar) {
- return instances
- .stream()
- .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId,
- ci -> convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), fromCsar)));
+ return instances.stream().collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId,
+ ci -> convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), fromCsar)));
}
public static Map<String, MapCapabilityProperty> extractCapabilityPropertiesFromGroups(List<GroupDefinition> groups, boolean fromCsar) {
if (CollectionUtils.isNotEmpty(groups)) {
- return groups
- .stream()
- .collect(Collectors.toMap(GroupDefinition::getUniqueId,
- g -> convertToMapOfMapCapabiltyProperties(g.getCapabilities(), g.getUniqueId(), fromCsar)));
+ return groups.stream().collect(Collectors
+ .toMap(GroupDefinition::getUniqueId, g -> convertToMapOfMapCapabiltyProperties(g.getCapabilities(), g.getUniqueId(), fromCsar)));
}
return Maps.newHashMap();
}
@@ -2154,12 +1929,7 @@ public class ModelConverter {
}
private static Map<String, ListCapabilityDataDefinition> buildMapOfListsOfCapabilities(GroupDefinition groupDefinition) {
- return groupDefinition.getCapabilities().entrySet()
- .stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> new ListCapabilityDataDefinition(e.getValue()
- .stream()
- .map(CapabilityDataDefinition::new)
- .collect(Collectors.toList()))));
+ return groupDefinition.getCapabilities().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
+ e -> new ListCapabilityDataDefinition(e.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))));
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/normatives/ToscaTypeMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/normatives/ToscaTypeMetadata.java
index 30f0a2db94..161e901b7b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/normatives/ToscaTypeMetadata.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/normatives/ToscaTypeMetadata.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.normatives;
public class ToscaTypeMetadata {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java
index 7ca574b0c2..328fd3a56c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations;
import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
@@ -25,7 +24,7 @@ import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-public class StorageException extends RuntimeException{
+public class StorageException extends RuntimeException {
private final StorageOperationStatus storageOperationStatus;
private final String[] params;
@@ -36,16 +35,14 @@ public class StorageException extends RuntimeException{
this.params = params;
}
- public StorageException(String message, Throwable cause, JanusGraphOperationStatus janusGraphOperationStatus, String... params){
+ public StorageException(String message, Throwable cause, JanusGraphOperationStatus janusGraphOperationStatus, String... params) {
super(message, cause);
- storageOperationStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- janusGraphOperationStatus);
+ storageOperationStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus);
this.params = params;
}
public StorageException(JanusGraphOperationStatus janusGraphOperationStatus, String... params) {
- storageOperationStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- janusGraphOperationStatus);
+ storageOperationStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus);
this.params = params;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/DerivedFromOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/DerivedFromOperation.java
index 360041be90..6a6d2ae1e7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/DerivedFromOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/DerivedFromOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,58 +17,51 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.api;
-
import fj.data.Either;
+import java.util.function.Function;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import java.util.function.Function;
-
public interface DerivedFromOperation {
/**
- *
- * @param parentUniqueId the unique id of the object which is the parent of the derived from object
+ * @param parentUniqueId the unique id of the object which is the parent of the derived from object
* @param derivedFromUniqueId the unique id of the derived from object
- * @param nodeType the type of the derived from and its parent objects
+ * @param nodeType the type of the derived from and its parent objects
* @return the status of the operation
*/
Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(String parentUniqueId, String derivedFromUniqueId, NodeTypeEnum nodeType);
-
+
/**
- *
* @param uniqueId the id of the entity of which to fetch its derived from object
* @param nodeType the type of the derived from object
- * @param clazz the class which represent the derived from object
+ * @param clazz the class which represent the derived from object
* @return the derived from object or error status of operation failed
*/
<T extends GraphNode> Either<T, StorageOperationStatus> getDerivedFromChild(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz);
/**
- *
- * @param uniqueId the id of the entity of which to remove its derived from object
+ * @param uniqueId the id of the entity of which to remove its derived from object
* @param derivedFromUniqueId the unique id of the derived from object
- * @param nodeType the type of the derived from and its parent objects
+ * @param nodeType the type of the derived from and its parent objects
* @return the status of the remove operation. if no derived from relation exists the operation is successful.
*/
StorageOperationStatus removeDerivedFromRelation(String uniqueId, String derivedFromUniqueId, NodeTypeEnum nodeType);
-
-
+
/**
* Checks whether childCandidateType is derived from parentCandidateType
*/
- public <T extends GraphNode> Either<Boolean, StorageOperationStatus> isTypeDerivedFrom(String childCandidateType, String parentCandidateType, String currentChildType,
- NodeTypeEnum capabilitytype, Class<T> clazz,
- Function<T, String> typeProvider);
+ public <T extends GraphNode> Either<Boolean, StorageOperationStatus> isTypeDerivedFrom(String childCandidateType, String parentCandidateType,
+ String currentChildType, NodeTypeEnum capabilitytype,
+ Class<T> clazz, Function<T, String> typeProvider);
/**
* Checks whether replacement of oldTypeParent hold in DERIVED FROM with newTypeParent is legal
*/
public <T extends GraphNode> StorageOperationStatus isUpdateParentAllowed(String oldTypeParent, String newTypeParent, String childType,
- NodeTypeEnum capabilitytype, Class<T> clazz,
- Function<T, String> typeProvider);
+ NodeTypeEnum capabilitytype, Class<T> clazz,
+ Function<T, String> typeProvider);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICacheMangerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICacheMangerOperation.java
index fcf5fab019..c41cd0f14f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICacheMangerOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICacheMangerOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.api;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -28,8 +27,6 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
public interface ICacheMangerOperation {
/**
- *
- *
* @param componentId
* @param timestamp
* @param nodeTypeEnum
@@ -37,5 +34,4 @@ public interface ICacheMangerOperation {
void updateComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum);
void storeComponentInCache(org.openecomp.sdc.be.model.Component component, NodeTypeEnum nodeTypeEnum);
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java
index 3525e1362e..ce2acdc1a8 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.api;
import fj.data.Either;
+import java.util.Map;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.model.PropertyDefinition;
-import java.util.Map;
-
public interface ICapabilityOperation {
Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType);
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java
index 780b9af70e..88485d7c74 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.api;
import fj.data.Either;
+import java.util.Map;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-import java.util.Map;
-
public interface ICapabilityTypeOperation {
/**
@@ -34,10 +32,11 @@ public interface ICapabilityTypeOperation {
*/
public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition);
- public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction);
-
-
- public Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityType(CapabilityTypeDefinition capabilityTypeDefNew, CapabilityTypeDefinition capabilityTypeDefOld);
+ public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition,
+ boolean inTransaction);
+
+ public Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityType(CapabilityTypeDefinition capabilityTypeDefNew,
+ CapabilityTypeDefinition capabilityTypeDefOld);
/**
* @param uniqueId
@@ -46,5 +45,6 @@ public interface ICapabilityTypeOperation {
public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId);
public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId, boolean inTransaction);
+
Either<Map<String, CapabilityTypeDefinition>, JanusGraphOperationStatus> getAllCapabilityTypes();
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java
index 55c38d05ab..e9c50bfed9 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.api;
import fj.data.Either;
-import org.openecomp.sdc.be.resources.data.ConsumerData;
-
import java.util.List;
+import org.openecomp.sdc.be.resources.data.ConsumerData;
public interface IConsumerOperation {
/**
* the method updates the node in the graph with the given ConsumerData
*
- * @param consumerData
- * the object we want to store
- * @param inTransaction
- * inTransaction is the operation part of a transaction, in case the value is false the action will be committed in the end of the method
+ * @param consumerData the object we want to store
+ * @param inTransaction inTransaction is the operation part of a transaction, in case the value is false the action will be committed in the end
+ * of the method
* @return the updated object returned from the graph
*/
Either<ConsumerData, StorageOperationStatus> updateCredentials(ConsumerData consumerData, boolean inTransaction);
@@ -41,8 +38,7 @@ public interface IConsumerOperation {
/**
* the method updates the node in the graph with the given ConsumerData
*
- * @param consumerData
- * the object we want to store
+ * @param consumerData the object we want to store
* @return the updated object returned from the graph
*/
Either<ConsumerData, StorageOperationStatus> updateCredentials(ConsumerData consumerData);
@@ -50,10 +46,9 @@ public interface IConsumerOperation {
/**
* the method deletes the node with the given unique id
*
- * @param consumerName
- * the unique id by witch we will look up the credential we want to delete
- * @param inTransaction
- * inTransaction is the operation part of a transaction, in case the value is false the action will be committed in the end of the method
+ * @param consumerName the unique id by witch we will look up the credential we want to delete
+ * @param inTransaction inTransaction is the operation part of a transaction, in case the value is false the action will be committed in the end
+ * of the method
* @return the deleted object returned from the graph
*/
Either<ConsumerData, StorageOperationStatus> deleteCredentials(String consumerName, boolean inTransaction);
@@ -61,8 +56,7 @@ public interface IConsumerOperation {
/**
* the method deletes the node with the given unique id
*
- * @param consumerName
- * the unique id by witch we will look up the credential we want to delete
+ * @param consumerName the unique id by witch we will look up the credential we want to delete
* @return the deleted object returned from the graph
*/
Either<ConsumerData, StorageOperationStatus> deleteCredentials(String consumerName);
@@ -70,10 +64,8 @@ public interface IConsumerOperation {
/**
* the method creates a new nod in the grape representing the supplied credential object
*
- * @param consumerData
- * the object we want to store
- * @param inTransaction
- * is the operation part of a transaction, in case the value is false the action will be committed in the end of the method
+ * @param consumerData the object we want to store
+ * @param inTransaction is the operation part of a transaction, in case the value is false the action will be committed in the end of the method
* @return the newly stored object returned from the graph
*/
Either<ConsumerData, StorageOperationStatus> createCredentials(ConsumerData consumerData, boolean inTransaction);
@@ -81,8 +73,7 @@ public interface IConsumerOperation {
/**
* the method creates a new nod in the grape representing the supplied credential object
*
- * @param consumerData
- * the object we want to store
+ * @param consumerData the object we want to store
* @return the newly stored object returned from the graph
*/
Either<ConsumerData, StorageOperationStatus> createCredentials(ConsumerData consumerData);
@@ -90,16 +81,13 @@ public interface IConsumerOperation {
/**
* the method retrieves the credential for the given consumer name
*
- * @param consumerName
- * the unique id by witch we will look up the credential
+ * @param consumerName the unique id by witch we will look up the credential
* @return ConsumerData or the error received during the operation
*/
Either<ConsumerData, StorageOperationStatus> getCredentials(String consumerName);
/**
- *
* @return all consumers
*/
Either<List<ConsumerData>, StorageOperationStatus> getAll();
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java
index 1851771f7d..1b89e86169 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.api;
import fj.data.Either;
@@ -40,5 +39,4 @@ public interface IDataTypeOperation {
public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(String name);
public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(String name, boolean inTransaction);
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java
index 38d5fcf6c8..b3f1306a04 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.api;
import fj.data.Either;
@@ -53,14 +52,16 @@ public interface IElementOperation {
<T extends GraphNode> Either<CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz);
- <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.category.CategoryData, StorageOperationStatus> getNewCategoryData(String name, NodeTypeEnum type, Class<T> clazz);
+ <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.category.CategoryData, StorageOperationStatus> getNewCategoryData(String name,
+ NodeTypeEnum type,
+ Class<T> clazz);
Either<Map<String, String>, ActionStatus> getResourceTypesMap();
Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType);
Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction);
-
+
Either<CategoryDefinition, ActionStatus> updateCategory(CategoryDefinition category, NodeTypeEnum nodeType);
Either<CategoryDefinition, ActionStatus> updateCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction);
@@ -73,11 +74,13 @@ public interface IElementOperation {
Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType);
- Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction);
-
+ Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType,
+ boolean inTransaction);
+
Either<SubCategoryDefinition, ActionStatus> updateSubCategory(String subCategoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType);
-
- Either<SubCategoryDefinition, ActionStatus> updateSubCategory(String subCategoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction);
+
+ Either<SubCategoryDefinition, ActionStatus> updateSubCategory(String subCategoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType,
+ boolean inTransaction);
Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java
index 8642ec8746..21288168b3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.api;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -31,5 +30,4 @@ public interface IGraphLockOperation {
StorageOperationStatus lockComponentByName(String name, NodeTypeEnum nodeType);
StorageOperationStatus unlockComponentByName(String name, String componentId, NodeTypeEnum nodeType);
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java
index 86be01d026..14eb2aecbf 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.api;
-
import fj.data.Either;
+import java.util.List;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.resources.data.ArtifactData;
-import java.util.List;
-
public interface IGroupInstanceOperation {
-
public Either<List<GroupInstance>, StorageOperationStatus> getAllGroupInstances(String componentInstId, NodeTypeEnum compInstNodeType);
public Either<Integer, StorageOperationStatus> increaseAndGetGroupInstancePropertyCounter(String groupInstanceId);
- public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction);
-
- public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction);
+ public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(
+ ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction);
- StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact);
+ public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(
+ ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction);
+ StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId,
+ ArtifactData newArtifact);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java
index 182adc881d..ccf7148f84 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,23 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.api;
import fj.data.Either;
+import java.util.List;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.resources.data.ArtifactData;
-import java.util.List;
-
public interface IGroupOperation {
- public Either<List<GraphRelation>, StorageOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId);
+ public Either<List<GraphRelation>, StorageOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId,
+ NodeTypeEnum componentTypeEnum,
+ String artifactId);
- public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction);
+ public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId,
+ ArtifactData newArtifact, boolean inTransaction);
public boolean isGroupExist(String groupName, boolean inTransaction);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java
index a82bfc81ca..d601a2fd49 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.api;
import fj.data.Either;
@@ -40,6 +39,4 @@ public interface IGroupTypeOperation {
Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String name, String version);
Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String name, String version, boolean inTransaction);
-
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IHeatParametersOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IHeatParametersOperation.java
index 8e573f6910..31ca8c5d7b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IHeatParametersOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IHeatParametersOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,29 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.api;
import fj.data.Either;
+import java.util.List;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
import org.openecomp.sdc.be.resources.data.HeatParameterValueData;
-import java.util.List;
-
public interface IHeatParametersOperation {
public StorageOperationStatus addPropertiesToGraph(List<HeatParameterDefinition> properties, String resourceId, NodeTypeEnum nodeType);
public StorageOperationStatus getHeatParametersOfNode(NodeTypeEnum nodeType, String uniqueId, List<HeatParameterDefinition> properties);
- public Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteAllHeatParametersAssociatedToNode(NodeTypeEnum nodeType, String uniqueId);
+ public Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteAllHeatParametersAssociatedToNode(NodeTypeEnum nodeType,
+ String uniqueId);
public StorageOperationStatus deleteAllHeatValuesAssociatedToNode(NodeTypeEnum parentNodeType, String parentUniqueId);
public StorageOperationStatus validateAndUpdateProperty(HeatParameterDefinition heatParam);
- public Either<HeatParameterValueData, StorageOperationStatus> updateHeatParameterValue(HeatParameterDefinition heatParam, String artifactId, String resourceInstanceId, String artifactLabel);
+ public Either<HeatParameterValueData, StorageOperationStatus> updateHeatParameterValue(HeatParameterDefinition heatParam, String artifactId,
+ String resourceInstanceId, String artifactLabel);
public StorageOperationStatus updateHeatParameters(List<HeatParameterDefinition> properties);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java
index 100916fe9e..aaa8ebd00f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.api;
import org.apache.commons.lang3.tuple.ImmutablePair;
@@ -30,5 +29,4 @@ public interface IInputsOperation {
ImmutablePair<JanusGraphOperationStatus, String> findInputValue(String resourceInstanceId, String propertyId);
ComponentInstanceInput buildResourceInstanceInput(InputValueData propertyValueData, ComponentInstanceInput resourceInstanceInput);
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java
index 06622ebba6..6783fcda13 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,34 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.api;
import fj.data.Either;
+import java.util.Map;
import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.Operation;
-import java.util.Map;
-
public interface IInterfaceLifecycleOperation {
- public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction);
+ public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId,
+ String interfaceName, boolean failIfExist,
+ boolean inTransaction);
- public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction);
+ public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId,
+ String interfaceName, boolean inTransaction);
- public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf);
+ public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName,
+ Operation interf);
- public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf, boolean inTransaction);
+ public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName,
+ Operation interf, boolean inTransaction);
- public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationName, boolean inTransaction);
+ public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationName,
+ boolean inTransaction);
- public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively, boolean inTransaction);
+ public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively,
+ boolean inTransaction);
public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively);
@@ -51,5 +56,5 @@ public interface IInterfaceLifecycleOperation {
public String getShortInterfaceName(InterfaceDataDefinition interfaceDefinition);
- Either<Map<String, InterfaceDefinition>,StorageOperationStatus> getAllInterfaceLifecycleTypes();
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfaceLifecycleTypes();
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java
index 3c0b85d840..bda3e95e0b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java
@@ -17,14 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.api;
import fj.data.Either;
-import org.openecomp.sdc.be.model.PolicyTypeDefinition;
-
import java.util.List;
import java.util.Set;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
public interface IPolicyTypeOperation {
@@ -32,8 +30,8 @@ public interface IPolicyTypeOperation {
Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyType);
- Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition updatedPolicyType, PolicyTypeDefinition currPolicyType);
+ Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition updatedPolicyType,
+ PolicyTypeDefinition currPolicyType);
List<PolicyTypeDefinition> getAllPolicyTypes(Set<String> excludedPolicyTypes);
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java
index effd195269..163ee43655 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.api;
import fj.data.Either;
+import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.IComplexDefaultValue;
import org.openecomp.sdc.be.model.PropertyDefinition;
-import java.util.Map;
-
public interface IPropertyOperation {
/**
@@ -38,10 +36,12 @@ public interface IPropertyOperation {
* @param uniqueId
* @return
*/
- public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId);
+ public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType,
+ String uniqueId);
/**
* same as deleteAllPropertiesAssociatedToNode but returns empty map if node has no properties
+ *
* @param nodeType
* @param uniqueId
* @return
@@ -52,7 +52,8 @@ public interface IPropertyOperation {
public boolean isPropertyTypeValid(IComplexDefaultValue propertyDefinition);
- public ImmutablePair<String, Boolean> isPropertyInnerTypeValid(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes);
+ public ImmutablePair<String, Boolean> isPropertyInnerTypeValid(IComplexDefaultValue propertyDefinition,
+ Map<String, DataTypeDefinition> dataTypes);
/**
* @param dataTypeDefinition
@@ -72,6 +73,6 @@ public interface IPropertyOperation {
public StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes);
- public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition);
-
+ public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition,
+ DataTypeDefinition oldDataTypeDefinition);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/StorageOperationStatus.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/StorageOperationStatus.java
index bb1096a900..3c8521ae79 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/StorageOperationStatus.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/StorageOperationStatus.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,52 +17,53 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.api;
public enum StorageOperationStatus {
- OK,
- CONNECTION_FAILURE,
- BAD_REQUEST,
- ENTITY_ALREADY_EXISTS,
- GRAPH_IS_LOCK,
- GENERAL_ERROR,
- USER_NOT_FOUND,
- PERMISSION_ERROR,
- HTTP_PROTOCOL_ERROR,
- STORAGE_NOT_AVAILABLE,
- READ_ONLY_STORAGE,
- STORAGE_LEGACY_INDEX_ERROR,
- SCHEMA_ERROR,
- TRANSACTION_ERROR,
- EXEUCTION_FAILED,
- NOT_FOUND,
- OPERATION_NOT_SUPPORTED,
- CATEGORY_NOT_FOUND,
- PARENT_RESOURCE_NOT_FOUND,
- MULTIPLE_PARENT_RESOURCE_FOUND,
- INCONSISTENCY,
- GRAPH_IS_NOT_AVAILABLE,
- SCHEMA_VIOLATION,
- FAILED_TO_LOCK_ELEMENT,
- INVALID_ID,
- MATCH_NOT_FOUND,
- ARTIFACT_NOT_FOUND,
- DISTR_ENVIRONMENT_NOT_AVAILABLE,
- DISTR_ENVIRONMENT_NOT_FOUND,
- DISTR_ENVIRONMENT_SENT_IS_INVALID,
- DISTR_ARTIFACT_NOT_FOUND,
- OVERLOAD,
- INVALID_TYPE,
- INVALID_VALUE,
- INVALID_INNER_TYPE,
- CSAR_NOT_FOUND,
- GROUP_INVALID_CONTENT,
- CANNOT_UPDATE_EXISTING_ENTITY,
- PROPERTY_NAME_ALREADY_EXISTS,
+ // @formatter:off
+ OK,
+ CONNECTION_FAILURE,
+ BAD_REQUEST,
+ ENTITY_ALREADY_EXISTS,
+ GRAPH_IS_LOCK,
+ GENERAL_ERROR,
+ USER_NOT_FOUND,
+ PERMISSION_ERROR,
+ HTTP_PROTOCOL_ERROR,
+ STORAGE_NOT_AVAILABLE,
+ READ_ONLY_STORAGE,
+ STORAGE_LEGACY_INDEX_ERROR,
+ SCHEMA_ERROR,
+ TRANSACTION_ERROR,
+ EXEUCTION_FAILED,
+ NOT_FOUND,
+ OPERATION_NOT_SUPPORTED,
+ CATEGORY_NOT_FOUND,
+ PARENT_RESOURCE_NOT_FOUND,
+ MULTIPLE_PARENT_RESOURCE_FOUND,
+ INCONSISTENCY,
+ GRAPH_IS_NOT_AVAILABLE,
+ SCHEMA_VIOLATION,
+ FAILED_TO_LOCK_ELEMENT,
+ INVALID_ID,
+ MATCH_NOT_FOUND,
+ ARTIFACT_NOT_FOUND,
+ DISTR_ENVIRONMENT_NOT_AVAILABLE,
+ DISTR_ENVIRONMENT_NOT_FOUND,
+ DISTR_ENVIRONMENT_SENT_IS_INVALID,
+ DISTR_ARTIFACT_NOT_FOUND,
+ OVERLOAD,
+ INVALID_TYPE,
+ INVALID_VALUE,
+ INVALID_INNER_TYPE,
+ CSAR_NOT_FOUND,
+ GROUP_INVALID_CONTENT,
+ CANNOT_UPDATE_EXISTING_ENTITY,
+ PROPERTY_NAME_ALREADY_EXISTS,
INVALID_PROPERTY,
COMPONENT_IS_ARCHIVED,
DECLARED_INPUT_USED_BY_OPERATION;
+ // @formatter:on
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/TypeOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/TypeOperations.java
index 75aef10c4b..c506a8ea03 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/TypeOperations.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/TypeOperations.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,28 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.api;
import fj.data.Either;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
import javax.validation.constraints.NotNull;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
public interface TypeOperations<T extends ToscaDataDefinition> {
+ static <T> Either<T, StorageOperationStatus> mapOkStatus(StorageOperationStatus status, T obj) {
+ return status != StorageOperationStatus.OK ? Either.right(status) : Either.left(obj);
+ }
+
T addType(T newTypeDefinition);
T getType(String uniqueId);
T getLatestType(String uniqueId);
- boolean isSameType(@NotNull T type1,@NotNull T type2);
+ boolean isSameType(@NotNull T type1, @NotNull T type2);
T updateType(T currentTypeDefinition, T newTypeDefinition);
-
- static <T> Either<T, StorageOperationStatus> mapOkStatus(StorageOperationStatus status, T obj) {
- return status != StorageOperationStatus.OK? Either.right(status) : Either.left(obj);
- }
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java
index 62f85e6b5f..1592782bfa 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
import com.google.gson.Gson;
@@ -56,55 +55,43 @@ import org.springframework.beans.factory.annotation.Autowired;
public abstract class AbstractOperation {
+ public static final String EMPTY_VALUE = null;
private static final Logger log = Logger.getLogger(AbstractOperation.class.getName());
-
@Autowired
protected HealingJanusGraphGenericDao janusGraphGenericDao;
-
- public static final String EMPTY_VALUE = null;
-
protected Gson gson = new Gson();
-
@Autowired
protected ApplicationDataTypeCache applicationDataTypeCache;
-
protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
- interface NodeElementFetcher<ElementDefinition> {
- JanusGraphOperationStatus findAllNodeElements(String nodeId, List<ElementDefinition> listTofill);
- }
-
- public <ElementDefinition> JanusGraphOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) {
-
- if (log.isTraceEnabled())
+ public <ElementDefinition> JanusGraphOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId,
+ List<ElementDefinition> elements,
+ NodeElementFetcher<ElementDefinition> singleNodeFetcher) {
+ if (log.isTraceEnabled()) {
log.trace("Going to fetch elements under resource {}", resourceId);
- JanusGraphOperationStatus
- resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements);
-
+ }
+ JanusGraphOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements);
if (resourceAttributesStatus != JanusGraphOperationStatus.OK) {
return resourceAttributesStatus;
}
-
Either<ImmutablePair<ResourceMetadataData, GraphEdge>, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
ResourceMetadataData.class);
-
if (parentNodes.isRight()) {
JanusGraphOperationStatus parentNodesStatus = parentNodes.right().value();
if (parentNodesStatus != JanusGraphOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively",
+ "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR);
return parentNodesStatus;
}
}
-
if (parentNodes.isLeft()) {
ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value();
String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId();
JanusGraphOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher);
-
if (addParentIntStatus != JanusGraphOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR);
-
+ BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively",
+ "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR);
return addParentIntStatus;
}
}
@@ -123,50 +110,36 @@ public abstract class AbstractOperation {
}
}
-
/**
* @param propertyDefinition
* @return
*/
-
protected StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
-
log.trace("Going to validate property type and value. {}", propertyDefinition);
-
String propertyType = propertyDefinition.getType();
String value = propertyDefinition.getDefaultValue();
-
ToscaPropertyType type = getType(propertyType);
-
if (type == null) {
-
DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
if (dataTypeDefinition == null) {
log.debug("The type {} of property cannot be found.", propertyType);
return StorageOperationStatus.INVALID_TYPE;
}
-
return validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
-
}
String innerType = null;
-
Either<String, JanusGraphOperationStatus> checkInnerType = getInnerType(type, propertyDefinition::getSchema);
if (checkInnerType.isRight()) {
return StorageOperationStatus.INVALID_TYPE;
}
innerType = checkInnerType.left().value();
-
log.trace("After validating property type {}", propertyType);
-
boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
if (!isValidProperty) {
log.info("The value {} of property from type {} is invalid", value, type);
return StorageOperationStatus.INVALID_VALUE;
}
-
PropertyValueConverter converter = type.getConverter();
-
if (isEmptyValue(value)) {
log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
propertyDefinition.setDefaultValue(EMPTY_VALUE);
@@ -178,18 +151,14 @@ public abstract class AbstractOperation {
}
protected ToscaPropertyType getType(String propertyType) {
-
return ToscaPropertyType.isValidType(propertyType);
-
}
protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
if (isEmptyValue(value)) {
return true;
}
-
PropertyTypeValidator validator = type.getValidator();
-
return validator.isValid(value, innerType, dataTypes);
}
@@ -197,30 +166,22 @@ public abstract class AbstractOperation {
return value == null;
}
- protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType,
-
- String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) {
-
+ protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType, String value,
+ DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) {
ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
-
if (!validateResult.right.booleanValue()) {
log.debug("The value {} of property from type {} is invalid", propertyType, propertyType);
return StorageOperationStatus.INVALID_VALUE;
}
-
JsonElement jsonElement = validateResult.left;
-
- log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null));
-
+ log.trace("Going to update value in property definition {} {}", propertyDefinition.getName(),
+ (jsonElement != null ? jsonElement.toString() : null));
updateValue(propertyDefinition, jsonElement);
-
return StorageOperationStatus.OK;
}
protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) {
-
propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement));
-
}
protected String getValueFromJsonElement(JsonElement jsonElement) {
@@ -234,7 +195,6 @@ public abstract class AbstractOperation {
protected Either<String, JanusGraphOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) {
String innerType = null;
if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
-
SchemaDefinition def = schemeGen.get();
if (def == null) {
log.debug("Schema doesn't exists for property of type {}", type);
@@ -257,26 +217,24 @@ public abstract class AbstractOperation {
* @return
*/
public List<String> convertConstraintsToString(List<PropertyConstraint> constraints) {
-
if (constraints == null || constraints.isEmpty()) {
return null;
}
-
return constraints.stream().map(gson::toJson).collect(Collectors.toList());
}
public List<PropertyConstraint> convertConstraints(List<String> constraints) {
-
if (constraints == null || constraints.isEmpty()) {
return null;
}
-
Type constraintType = new TypeToken<PropertyConstraint>() {
}.getType();
-
Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
-
return constraints.stream().map(c -> gson.fromJson(c, PropertyConstraint.class)).collect(Collectors.toList());
}
+ interface NodeElementFetcher<ElementDefinition> {
+
+ JanusGraphOperationStatus findAllNodeElements(String nodeId, List<ElementDefinition> listTofill);
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java
index 68fc5977c4..ee4f73629c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,26 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
-import org.janusgraph.core.JanusGraphVertex;
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 org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.janusgraph.core.JanusGraphVertex;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -45,47 +49,35 @@ import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Component;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
@Component("additional-information-operation")
public class AdditionalInformationOperation {
+ public static final String EMPTY_VALUE = null;
private static final Logger log = Logger.getLogger(AdditionalInformationOperation.class.getName());
-
+ private static final String GOING_TO_EXECUTE_COMMIT_ON_GRAPH = "Going to execute commit on graph.";
+ private static final String GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH = "Going to execute rollback on graph.";
+ private static final String ADDITIONAL_INFORMATION_OF = "additional information of ";
@javax.annotation.Resource
private JanusGraphGenericDao janusGraphGenericDao;
- private static final String GOING_TO_EXECUTE_COMMIT_ON_GRAPH = "Going to execute commit on graph.";
- private static final String GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH = "Going to execute rollback on graph.";
- private static final String ADDITIONAL_INFORMATION_OF = "additional information of ";
- public static final String EMPTY_VALUE = null;
-
public AdditionalInformationOperation() {
super();
}
-
- public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> addAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String key, String value) {
-
- JanusGraphOperationStatus
- verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
+ public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> addAdditionalInformationParameter(NodeTypeEnum nodeType,
+ String componentId, String key,
+ String value) {
+ JanusGraphOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
if (verifyNodeTypeVsComponent != JanusGraphOperationStatus.OK) {
return Either.right(verifyNodeTypeVsComponent);
}
-
Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, JanusGraphOperationStatus> getResult = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
-
if (getResult.isRight()) {
JanusGraphOperationStatus status = getResult.right().value();
return Either.right(status);
}
-
ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value();
AdditionalInfoParameterData parameterData = immutablePair.getLeft();
Map<String, String> parameters = parameterData.getParameters();
@@ -98,51 +90,42 @@ public class AdditionalInformationOperation {
idToKey = new HashMap<>();
parameterData.setIdToKey(idToKey);
}
-
Integer lastCreatedCounter = parameterData.getAdditionalInfoParameterDataDefinition().getLastCreatedCounter();
lastCreatedCounter++;
-
if (parameters.containsKey(key)) {
log.debug("The key {} already exists under component {}", key, componentId);
return Either.right(JanusGraphOperationStatus.ALREADY_EXIST);
}
-
idToKey.put(String.valueOf(lastCreatedCounter), key);
parameters.put(key, value);
parameterData.getAdditionalInfoParameterDataDefinition().setLastCreatedCounter(lastCreatedCounter);
-
Either<AdditionalInfoParameterData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao
.updateNode(parameterData, AdditionalInfoParameterData.class);
-
if (updateNode.isRight()) {
JanusGraphOperationStatus status = updateNode.right().value();
- BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status));
+ BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter",
+ ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status));
return Either.right(status);
}
-
- AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value());
-
+ AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey,
+ updateNode.left().value());
return Either.left(informationDefinition);
-
}
- public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id, String key, String value) {
-
- JanusGraphOperationStatus
- verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
+ public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType,
+ String componentId, String id,
+ String key, String value) {
+ JanusGraphOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
if (verifyNodeTypeVsComponent != JanusGraphOperationStatus.OK) {
return Either.right(verifyNodeTypeVsComponent);
}
-
Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, JanusGraphOperationStatus> getResult = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
-
if (getResult.isRight()) {
JanusGraphOperationStatus status = getResult.right().value();
return Either.right(status);
}
-
ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value();
AdditionalInfoParameterData parameterData = immutablePair.getLeft();
Map<String, String> parameters = parameterData.getParameters();
@@ -150,9 +133,7 @@ public class AdditionalInformationOperation {
if (idToKey == null || !idToKey.containsKey(id)) {
return Either.right(JanusGraphOperationStatus.INVALID_ID);
}
-
String origKey = idToKey.get(id);
-
if (!origKey.equals(key)) {
if (parameters.containsKey(key)) {
log.debug("The key {} already exists", key);
@@ -163,105 +144,85 @@ public class AdditionalInformationOperation {
}
parameters.put(key, value);
idToKey.put(id, key);
-
Either<AdditionalInfoParameterData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao
.updateNode(parameterData, AdditionalInfoParameterData.class);
-
if (updateNode.isRight()) {
JanusGraphOperationStatus status = updateNode.right().value();
- BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", "additional information of resource " + componentId, String.valueOf(status));
+ BeEcompErrorManager.getInstance()
+ .logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", "additional information of resource " + componentId,
+ String.valueOf(status));
return Either.right(status);
}
-
- AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value());
-
+ AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey,
+ updateNode.left().value());
return Either.left(informationDefinition);
-
}
- public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) {
-
- JanusGraphOperationStatus
- verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
+ public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType,
+ String componentId, String id) {
+ JanusGraphOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
if (verifyNodeTypeVsComponent != JanusGraphOperationStatus.OK) {
return Either.right(verifyNodeTypeVsComponent);
}
-
Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, JanusGraphOperationStatus> getResult = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
-
if (getResult.isRight()) {
JanusGraphOperationStatus status = getResult.right().value();
return Either.right(status);
}
-
ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value();
AdditionalInfoParameterData parameterData = immutablePair.getLeft();
Map<String, String> parameters = parameterData.getParameters();
Map<String, String> idToKey = parameterData.getIdToKey();
-
if (idToKey == null || !idToKey.containsKey(id)) {
return Either.right(JanusGraphOperationStatus.INVALID_ID);
}
-
String key = idToKey.get(id);
String removedKey = idToKey.remove(id);
String removedValue = parameters.remove(key);
log.trace("The key-value {} = {} was removed from additionalInformation", removedKey, removedValue);
-
Either<AdditionalInfoParameterData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao
.updateNode(parameterData, AdditionalInfoParameterData.class);
-
if (updateNode.isRight()) {
JanusGraphOperationStatus status = updateNode.right().value();
- BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("DeleteAdditionalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status));
+ BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("DeleteAdditionalInformationParameter",
+ ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status));
return Either.right(status);
}
-
- AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value());
-
+ AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey,
+ updateNode.left().value());
return Either.left(informationDefinition);
-
}
- private AdditionalInformationDefinition createInformationDefinitionFromNode(String resourceId, Map<String, String> parameters, Map<String, String> idToKey, AdditionalInfoParameterData additionalInfoParameterData) {
+ private AdditionalInformationDefinition createInformationDefinitionFromNode(String resourceId, Map<String, String> parameters,
+ Map<String, String> idToKey,
+ AdditionalInfoParameterData additionalInfoParameterData) {
AdditionalInfoParameterDataDefinition dataDefinition = additionalInfoParameterData.getAdditionalInfoParameterDataDefinition();
-
return new AdditionalInformationDefinition(dataDefinition, resourceId, convertParameters(parameters, idToKey));
}
private List<AdditionalInfoParameterInfo> convertParameters(Map<String, String> parameters, Map<String, String> idToKey) {
-
List<AdditionalInfoParameterInfo> list = new ArrayList<>();
-
if (parameters != null) {
for (Entry<String, String> idToKeyEntry : idToKey.entrySet()) {
-
String id = idToKeyEntry.getKey();
String key = idToKeyEntry.getValue();
-
String value = parameters.get(key);
-
AdditionalInfoParameterInfo parameterInfo = new AdditionalInfoParameterInfo(id, key, value);
list.add(parameterInfo);
}
-
}
-
return list;
}
public Either<AdditionalInfoParameterData, JanusGraphOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId) {
-
UniqueIdData from = new UniqueIdData(nodeType, componentId);
-
String uniqueId = UniqueIdBuilder.buildAdditionalInformationUniqueId(componentId);
AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition();
additionalInfoParameterDataDefinition.setUniqueId(uniqueId);
-
- AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<>(), new HashMap<>());
-
+ AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition,
+ new HashMap<>(), new HashMap<>());
Either<AdditionalInfoParameterData, JanusGraphOperationStatus> createNode = janusGraphGenericDao
.createNode(additionalInfoParameterData, AdditionalInfoParameterData.class);
if (createNode.isRight()) {
@@ -269,104 +230,82 @@ public class AdditionalInformationOperation {
BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status));
return Either.right(status);
}
-
AdditionalInfoParameterData to = createNode.left().value();
-
Either<GraphRelation, JanusGraphOperationStatus> createRelation = janusGraphGenericDao
.createRelation(from, to, GraphEdgeLabels.ADDITIONAL_INFORMATION, null);
if (createRelation.isRight()) {
JanusGraphOperationStatus status = createRelation.right().value();
return Either.right(status);
}
-
return Either.left(to);
}
- public Either<JanusGraphVertex, JanusGraphOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, JanusGraphVertex metadataVertex) {
-
+ public Either<JanusGraphVertex, JanusGraphOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId,
+ JanusGraphVertex metadataVertex) {
String uniqueId = UniqueIdBuilder.buildAdditionalInformationUniqueId(componentId);
AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition();
additionalInfoParameterDataDefinition.setUniqueId(uniqueId);
-
- AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<>(), new HashMap<>());
-
+ AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition,
+ new HashMap<>(), new HashMap<>());
Either<JanusGraphVertex, JanusGraphOperationStatus> createNode = janusGraphGenericDao.createNode(additionalInfoParameterData);
if (createNode.isRight()) {
JanusGraphOperationStatus status = createNode.right().value();
BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status));
return Either.right(status);
}
-
JanusGraphVertex additionalInfoVertex = createNode.left().value();
-
JanusGraphOperationStatus createRelation = janusGraphGenericDao
.createEdge(metadataVertex, additionalInfoVertex, GraphEdgeLabels.ADDITIONAL_INFORMATION, null);
-
if (!createRelation.equals(JanusGraphOperationStatus.OK)) {
return Either.right(createRelation);
}
return Either.left(additionalInfoVertex);
}
- public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters) {
-
+ public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId,
+ AdditionalInformationDefinition parameters) {
Either<AdditionalInfoParameterData, JanusGraphOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId);
-
if (status.isRight()) {
return Either.right(status.right().value());
}
-
AdditionalInfoParameterData parameterData = status.left().value();
-
populateParameterNodeWithParameters(parameterData, parameters);
-
Either<AdditionalInfoParameterData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao
.updateNode(parameterData, AdditionalInfoParameterData.class);
-
if (updateNode.isRight()) {
return Either.right(updateNode.right().value());
}
-
AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(updateNode.left().value(), componentId);
-
return Either.left(informationDefinition);
}
- public JanusGraphOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, JanusGraphVertex metadataVertex) {
-
+ public JanusGraphOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId,
+ AdditionalInformationDefinition parameters, JanusGraphVertex metadataVertex) {
Either<JanusGraphVertex, JanusGraphOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId, metadataVertex);
-
if (status.isRight()) {
return status.right().value();
}
JanusGraphVertex additionalInfoVertex = status.left().value();
-
Map<String, Object> newProp = janusGraphGenericDao.getProperties(additionalInfoVertex);
- AdditionalInfoParameterData parameterData = GraphElementFactory.createElement(NodeTypeEnum.AdditionalInfoParameters.getName(), GraphElementTypeEnum.Node, newProp, AdditionalInfoParameterData.class);
-
+ AdditionalInfoParameterData parameterData = GraphElementFactory
+ .createElement(NodeTypeEnum.AdditionalInfoParameters.getName(), GraphElementTypeEnum.Node, newProp, AdditionalInfoParameterData.class);
populateParameterNodeWithParameters(parameterData, parameters);
-
return janusGraphGenericDao.updateVertex(parameterData, additionalInfoVertex);
}
private void populateParameterNodeWithParameters(AdditionalInfoParameterData parameterData, AdditionalInformationDefinition aiDefinition) {
-
if (aiDefinition != null) {
-
Integer lastCreatedCounter = aiDefinition.getLastCreatedCounter();
parameterData.getAdditionalInfoParameterDataDefinition().setLastCreatedCounter(lastCreatedCounter);
log.trace("Set last created counter of additional information to {}", lastCreatedCounter);
-
List<AdditionalInfoParameterInfo> parameters = aiDefinition.getParameters();
if (parameters != null) {
-
Map<String, String> idToKey = new HashMap<>();
Map<String, String> parametersMap = new HashMap<>();
for (AdditionalInfoParameterInfo additionalInfoParameterInfo : parameters) {
String uniqueId = additionalInfoParameterInfo.getUniqueId();
String key = additionalInfoParameterInfo.getKey();
String value = additionalInfoParameterInfo.getValue();
-
if (key != null && !key.isEmpty()) {
idToKey.put(uniqueId, key);
parametersMap.put(key, value);
@@ -376,22 +315,18 @@ public class AdditionalInformationOperation {
parameterData.setParameters(parametersMap);
}
}
-
}
- public JanusGraphOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) {
-
+ public JanusGraphOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId,
+ List<AdditionalInformationDefinition> properties) {
log.trace("Going to fetch additional information under resource {}", uniqueId);
JanusGraphOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Resource, uniqueId, properties);
-
if (!resourceCapabilitiesStatus.equals(JanusGraphOperationStatus.OK)) {
return resourceCapabilitiesStatus;
}
-
Either<ImmutablePair<ResourceMetadataData, GraphEdge>, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
ResourceMetadataData.class);
-
if (parentNodes.isRight()) {
JanusGraphOperationStatus parentNodesStatus = parentNodes.right().value();
if (!parentNodesStatus.equals(JanusGraphOperationStatus.NOT_FOUND)) {
@@ -399,34 +334,28 @@ public class AdditionalInformationOperation {
return parentNodesStatus;
}
}
-
if (parentNodes.isLeft()) {
ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value();
String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId();
JanusGraphOperationStatus addParentIntStatus = findResourceAllAdditionalInformationRecursively(parentUniqueId, properties);
-
if (addParentIntStatus != JanusGraphOperationStatus.OK) {
log.error("Failed to find all resource additional information of resource {}", parentUniqueId);
return addParentIntStatus;
}
}
return JanusGraphOperationStatus.OK;
-
}
- public JanusGraphOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) {
-
+ public JanusGraphOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId,
+ List<AdditionalInformationDefinition> properties) {
log.trace("Going to fetch additional information under service {}", uniqueId);
JanusGraphOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Service, uniqueId, properties);
-
if (!resourceCapabilitiesStatus.equals(JanusGraphOperationStatus.OK)) {
return resourceCapabilitiesStatus;
}
-
Either<ImmutablePair<ServiceMetadataData, GraphEdge>, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Service,
ServiceMetadataData.class);
-
if (parentNodes.isRight()) {
JanusGraphOperationStatus parentNodesStatus = parentNodes.right().value();
if (!parentNodesStatus.equals(JanusGraphOperationStatus.NOT_FOUND)) {
@@ -434,27 +363,23 @@ public class AdditionalInformationOperation {
return parentNodesStatus;
}
}
-
if (parentNodes.isLeft()) {
ImmutablePair<ServiceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value();
String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId();
JanusGraphOperationStatus addParentIntStatus = findServiceAllAdditionalInformationRecursively(parentUniqueId, properties);
-
if (addParentIntStatus != JanusGraphOperationStatus.OK) {
log.error("Failed to find all resource additional information of resource {}", parentUniqueId);
return addParentIntStatus;
}
}
return JanusGraphOperationStatus.OK;
-
}
- private JanusGraphOperationStatus findAdditionalInformationOfNode(NodeTypeEnum nodeType, String uniqueId, List<AdditionalInformationDefinition> properties) {
-
+ private JanusGraphOperationStatus findAdditionalInformationOfNode(NodeTypeEnum nodeType, String uniqueId,
+ List<AdditionalInformationDefinition> properties) {
Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, JanusGraphOperationStatus> childNode = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
-
if (childNode.isRight()) {
JanusGraphOperationStatus status = childNode.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -462,61 +387,55 @@ public class AdditionalInformationOperation {
}
return status;
}
-
ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = childNode.left().value();
AdditionalInfoParameterData propertyData = immutablePair.getKey();
-
Map<String, String> parameters = propertyData.getParameters();
if (parameters != null && !parameters.isEmpty()) {
AdditionalInformationDefinition additionalInfoDef = this.convertAdditionalInformationDataToDefinition(propertyData, uniqueId);
properties.add(additionalInfoDef);
}
-
return JanusGraphOperationStatus.OK;
-
}
- private AdditionalInformationDefinition convertAdditionalInformationDataToDefinition(AdditionalInfoParameterData additionalInfoData, String uniqueId) {
-
+ private AdditionalInformationDefinition convertAdditionalInformationDataToDefinition(AdditionalInfoParameterData additionalInfoData,
+ String uniqueId) {
Map<String, String> parameters = additionalInfoData.getParameters();
Map<String, String> idToKey = additionalInfoData.getIdToKey();
-
- return new AdditionalInformationDefinition(additionalInfoData.getAdditionalInfoParameterDataDefinition(), uniqueId, convertParameters(parameters, idToKey));
+ return new AdditionalInformationDefinition(additionalInfoData.getAdditionalInfoParameterDataDefinition(), uniqueId,
+ convertParameters(parameters, idToKey));
}
- public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction) {
-
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter(NodeTypeEnum nodeType,
+ String resourceId, String key,
+ String value, boolean inTransaction) {
Either<AdditionalInformationDefinition, StorageOperationStatus> result = null;
-
try {
-
- Either<AdditionalInformationDefinition, JanusGraphOperationStatus> either = this.addAdditionalInformationParameter(nodeType, resourceId, key, value);
-
+ Either<AdditionalInformationDefinition, JanusGraphOperationStatus> either = this
+ .addAdditionalInformationParameter(nodeType, resourceId, key, value);
if (either.isRight()) {
JanusGraphOperationStatus status = either.right().value();
log.debug("Failed to add additional information property {} to component {}. Status is {}", key, resourceId, status);
- BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("CreateAdditionalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + resourceId, String.valueOf(status));
+ BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("CreateAdditionalInformationParameter",
+ ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + resourceId, String.valueOf(status));
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
} else {
AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
result = Either.left(additionalInformationDefinition);
}
-
return result;
} finally {
commitOrRollback(inTransaction, result);
}
-
}
- public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction) {
-
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType,
+ String resourceId, String id,
+ String key, String value,
+ boolean inTransaction) {
Either<AdditionalInformationDefinition, StorageOperationStatus> result = null;
-
try {
-
- Either<AdditionalInformationDefinition, JanusGraphOperationStatus> either = this.updateAdditionalInformationParameter(nodeType, resourceId, id, key, value);
-
+ Either<AdditionalInformationDefinition, JanusGraphOperationStatus> either = this
+ .updateAdditionalInformationParameter(nodeType, resourceId, id, key, value);
if (either.isRight()) {
log.info("Failed to update additional information property {} to component {}", key, resourceId);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value()));
@@ -524,23 +443,19 @@ public class AdditionalInformationOperation {
AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
result = Either.left(additionalInformationDefinition);
}
-
return result;
-
} finally {
commitOrRollback(inTransaction, result);
}
-
}
- public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) {
-
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType,
+ String resourceId, String id,
+ boolean inTransaction) {
Either<AdditionalInformationDefinition, StorageOperationStatus> result = null;
-
try {
-
- Either<AdditionalInformationDefinition, JanusGraphOperationStatus> either = this.deleteAdditionalInformationParameter(nodeType, resourceId, id);
-
+ Either<AdditionalInformationDefinition, JanusGraphOperationStatus> either = this
+ .deleteAdditionalInformationParameter(nodeType, resourceId, id);
if (either.isRight()) {
log.error("Failed to delete additional information id {} to component {}", id, resourceId);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value()));
@@ -548,23 +463,17 @@ public class AdditionalInformationOperation {
AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
result = Either.left(additionalInformationDefinition);
}
-
return result;
-
} finally {
commitOrRollback(inTransaction, result);
}
-
}
- public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) {
-
+ public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId,
+ boolean inTransaction) {
Either<Integer, StorageOperationStatus> result = null;
-
try {
-
Either<Integer, JanusGraphOperationStatus> either = this.getNumberOfParameters(nodeType, resourceId);
-
if (either.isRight()) {
log.error("Failed to get the number of additional information properties in component {}", resourceId);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value()));
@@ -572,7 +481,6 @@ public class AdditionalInformationOperation {
Integer counter = either.left().value();
result = Either.left(counter);
}
-
return result;
} finally {
if (!inTransaction) {
@@ -585,122 +493,99 @@ public class AdditionalInformationOperation {
}
}
}
-
}
public Either<Integer, JanusGraphOperationStatus> getNumberOfParameters(NodeTypeEnum nodeType, String resourceId) {
-
Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, JanusGraphOperationStatus> getResult = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
-
if (getResult.isRight()) {
JanusGraphOperationStatus status = getResult.right().value();
return Either.right(status);
}
-
ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value();
AdditionalInfoParameterData parameterData = immutablePair.getLeft();
Map<String, String> parameters = parameterData.getParameters();
-
Integer counter = 0;
if (parameters != null) {
counter = parameters.size();
}
-
return Either.left(counter);
-
}
- public Either<AdditionalInfoParameterInfo, JanusGraphOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) {
-
- JanusGraphOperationStatus
- verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
+ public Either<AdditionalInfoParameterInfo, JanusGraphOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId,
+ String id) {
+ JanusGraphOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
if (verifyNodeTypeVsComponent != JanusGraphOperationStatus.OK) {
return Either.right(verifyNodeTypeVsComponent);
}
-
Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, JanusGraphOperationStatus> getResult = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
-
if (getResult.isRight()) {
JanusGraphOperationStatus status = getResult.right().value();
return Either.right(status);
}
-
ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value();
AdditionalInfoParameterData parameterData = immutablePair.getLeft();
Map<String, String> parameters = parameterData.getParameters();
Map<String, String> idToKey = parameterData.getIdToKey();
-
if (idToKey == null || !idToKey.containsKey(id)) {
return Either.right(JanusGraphOperationStatus.INVALID_ID);
}
-
String key = idToKey.get(id);
String value = parameters.get(key);
-
log.trace("The key-value {} = {} was retrieved for id {}", key, value, id);
-
Either<AdditionalInfoParameterData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao
.updateNode(parameterData, AdditionalInfoParameterData.class);
-
if (updateNode.isRight()) {
JanusGraphOperationStatus status = updateNode.right().value();
if (status != JanusGraphOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status));
+ BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameter",
+ ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status));
}
return Either.right(status);
}
-
AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(id, key, value);
-
return Either.left(additionalInfoParameterInfo);
-
}
- public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String componentId, boolean ignoreVerification) {
-
+ public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType,
+ String componentId,
+ boolean ignoreVerification) {
if (!ignoreVerification) {
- JanusGraphOperationStatus
- verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
+ JanusGraphOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId);
if (verifyNodeTypeVsComponent != JanusGraphOperationStatus.OK) {
return Either.right(verifyNodeTypeVsComponent);
}
}
-
Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, JanusGraphOperationStatus> getResult = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
-
if (getResult.isRight()) {
JanusGraphOperationStatus status = getResult.right().value();
if (status != JanusGraphOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameters", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status));
+ BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameters",
+ ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status));
}
return Either.right(status);
}
-
ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value();
AdditionalInfoParameterData parameterData = immutablePair.getLeft();
Map<String, String> parameters = parameterData.getParameters();
Map<String, String> idToKey = parameterData.getIdToKey();
-
AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, parameterData);
-
return Either.left(informationDefinition);
-
}
- public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction) {
-
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType,
+ String resourceId,
+ boolean ignoreVerification,
+ boolean inTransaction) {
Either<AdditionalInformationDefinition, StorageOperationStatus> result = null;
-
try {
-
- Either<AdditionalInformationDefinition, JanusGraphOperationStatus> either = this.getAllAdditionalInformationParameters(nodeType, resourceId, ignoreVerification);
-
+ Either<AdditionalInformationDefinition, JanusGraphOperationStatus> either = this
+ .getAllAdditionalInformationParameters(nodeType, resourceId, ignoreVerification);
if (either.isRight()) {
JanusGraphOperationStatus status = either.right().value();
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
@@ -708,17 +593,13 @@ public class AdditionalInformationOperation {
AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
result = Either.left(additionalInformationDefinition);
}
-
return result;
-
} finally {
commitOrRollback(inTransaction, result);
}
-
}
private void commitOrRollback(boolean inTransaction, Either<? extends Object, StorageOperationStatus> result) {
-
if (!inTransaction) {
if (result == null || result.isRight()) {
log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
@@ -729,16 +610,12 @@ public class AdditionalInformationOperation {
}
}
}
-
-
- public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) {
+ public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId,
+ String id, boolean inTransaction) {
Either<AdditionalInfoParameterInfo, StorageOperationStatus> result = null;
-
try {
-
Either<AdditionalInfoParameterInfo, JanusGraphOperationStatus> either = this.getAdditionalInformationParameter(nodeType, resourceId, id);
-
if (either.isRight()) {
log.error("Failed to fetch additional information property with id {} of component {}", id, resourceId);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value()));
@@ -746,53 +623,46 @@ public class AdditionalInformationOperation {
AdditionalInfoParameterInfo additionalInformationDefinition = either.left().value();
result = Either.left(additionalInformationDefinition);
}
-
return result;
-
} finally {
commitOrRollback(inTransaction, result);
}
}
- public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) {
-
+ public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters(NodeTypeEnum nodeType,
+ String resourceId,
+ boolean inTransaction) {
Either<AdditionalInformationDefinition, StorageOperationStatus> result = null;
-
try {
-
Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, JanusGraphOperationStatus> getResult = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION,
NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class);
-
if (getResult.isRight()) {
JanusGraphOperationStatus status = getResult.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
return Either.right(StorageOperationStatus.OK);
} else {
- BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + resourceId, String.valueOf(status));
+ BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode",
+ ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + resourceId, String.valueOf(status));
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
return result;
}
-
ImmutablePair<AdditionalInfoParameterData, GraphEdge> value = getResult.left().value();
AdditionalInfoParameterData parameterData = value.getLeft();
-
Either<AdditionalInfoParameterData, JanusGraphOperationStatus> deleteNodeRes = janusGraphGenericDao
.deleteNode(parameterData, AdditionalInfoParameterData.class);
if (deleteNodeRes.isRight()) {
JanusGraphOperationStatus status = getResult.right().value();
- BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", (String) parameterData.getUniqueId(), String.valueOf(status));
+ BeEcompErrorManager.getInstance()
+ .logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", (String) parameterData.getUniqueId(), String.valueOf(status));
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
return result;
}
-
- AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(deleteNodeRes.left().value(), resourceId);
-
+ AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(deleteNodeRes.left().value(),
+ resourceId);
result = Either.left(informationDefinition);
-
return result;
-
} finally {
commitOrRollback(inTransaction, result);
}
@@ -822,5 +692,4 @@ public class AdditionalInformationOperation {
}
return JanusGraphOperationStatus.OK;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperations.java
index c15613c374..2d48aede4b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperations.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperations.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
+import javax.validation.constraints.NotNull;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.AnnotationTypeDefinition;
import org.openecomp.sdc.be.model.operations.api.TypeOperations;
import org.openecomp.sdc.be.resources.data.AnnotationTypeData;
import org.springframework.stereotype.Component;
-import javax.validation.constraints.NotNull;
-
@Component
public class AnnotationTypeOperations implements TypeOperations<AnnotationTypeDefinition> {
@@ -49,22 +47,21 @@ public class AnnotationTypeOperations implements TypeOperations<AnnotationTypeDe
@Override
public AnnotationTypeDefinition getType(String uniqueId) {
- return commonTypeOperations.getType(uniqueId, AnnotationTypeData.class, NodeTypeEnum.AnnotationType)
- .map(this::populateTypeDefinition)
- .orElse(null);
+ return commonTypeOperations.getType(uniqueId, AnnotationTypeData.class, NodeTypeEnum.AnnotationType).map(this::populateTypeDefinition)
+ .orElse(null);
}
private AnnotationTypeDefinition populateTypeDefinition(@NotNull AnnotationTypeData annotationTypeData) {
AnnotationTypeDefinition annotationTypeDefinition = new AnnotationTypeDefinition(annotationTypeData.getAnnotationTypeDataDefinition());
- commonTypeOperations.fillProperties(annotationTypeDefinition.getUniqueId(), NodeTypeEnum.AnnotationType, annotationTypeDefinition::setProperties);
+ commonTypeOperations
+ .fillProperties(annotationTypeDefinition.getUniqueId(), NodeTypeEnum.AnnotationType, annotationTypeDefinition::setProperties);
return annotationTypeDefinition;
}
@Override
public AnnotationTypeDefinition getLatestType(String type) {
- return commonTypeOperations.getLatestType(type, AnnotationTypeData.class, NodeTypeEnum.AnnotationType)
- .map(this::populateTypeDefinition)
- .orElse(null);
+ return commonTypeOperations.getLatestType(type, AnnotationTypeData.class, NodeTypeEnum.AnnotationType).map(this::populateTypeDefinition)
+ .orElse(null);
}
@Override
@@ -73,12 +70,11 @@ public class AnnotationTypeOperations implements TypeOperations<AnnotationTypeDe
}
@Override
- public AnnotationTypeDefinition updateType(AnnotationTypeDefinition currentTypeDefinition,
- AnnotationTypeDefinition updatedTypeDefinition) {
+ public AnnotationTypeDefinition updateType(AnnotationTypeDefinition currentTypeDefinition, AnnotationTypeDefinition updatedTypeDefinition) {
AnnotationTypeData updatedTypeData = new AnnotationTypeData(updatedTypeDefinition);
updatedTypeData.setUpdateProperties(currentTypeDefinition);
- commonTypeOperations.updateType(updatedTypeData, updatedTypeDefinition.getProperties(), AnnotationTypeData.class, NodeTypeEnum.AnnotationType);
+ commonTypeOperations
+ .updateType(updatedTypeData, updatedTypeDefinition.getProperties(), AnnotationTypeData.class, NodeTypeEnum.AnnotationType);
return getType(updatedTypeData.getUniqueId());
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java
index 102e896c38..4378001027 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,27 +17,32 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphVertex;
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.UUID;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphVertex;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
@@ -53,156 +58,142 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
-import java.util.*;
-
@Component("artifact-operation")
public class ArtifactOperation {
private static final String THE_RETURNED_ARTIFACT_DEFINTION_IS = "The returned ArtifactDefintion is {}";
-
- @javax.annotation.Resource
+ private static final Logger log = Logger.getLogger(ArtifactOperation.class.getName());
+ @javax.annotation.Resource
private JanusGraphGenericDao janusGraphGenericDao;
-
@javax.annotation.Resource
private HeatParametersOperation heatParametersOperation;
-
@javax.annotation.Resource
private GroupOperation groupOperation;
@javax.annotation.Resource
private GroupInstanceOperation groupInstanceOperation;
- private static final Logger log = Logger.getLogger(ArtifactOperation.class.getName());
-
public ArtifactOperation() {
super();
}
- public Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, boolean inTransaction) {
-
+ public Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent(ArtifactDefinition artifactInfo, String parentId,
+ NodeTypeEnum type, boolean failIfExist, boolean inTransaction) {
Either<ArtifactData, StorageOperationStatus> status = addArtifactToGraph(artifactInfo, parentId, type, failIfExist);
-
if (status.isRight()) {
if (!inTransaction) {
janusGraphGenericDao.rollback();
}
- log.debug("Failed to add artifact {} to {} {}", artifactInfo.getArtifactName(), type , parentId);
+ log.debug("Failed to add artifact {} to {} {}", artifactInfo.getArtifactName(), type, parentId);
return Either.right(status.right().value());
} else {
if (!inTransaction) {
janusGraphGenericDao.commit();
}
ArtifactData artifactData = status.left().value();
-
ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);
-
log.debug(THE_RETURNED_ARTIFACT_DEFINTION_IS, artifactDefResult);
return Either.left(artifactDefResult);
}
-
}
- private Either<ArtifactData, StorageOperationStatus> addArtifactToGraph(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type, boolean failIfexist) {
-
+ private Either<ArtifactData, StorageOperationStatus> addArtifactToGraph(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type,
+ boolean failIfexist) {
if (artifactInfo.getUniqueId() == null || artifactInfo.getUniqueId().isEmpty()) {
String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel());
artifactInfo.setUniqueId(uniqueId);
}
-
if (!validateParentType(type)) {
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
-
ArtifactData artifactData = new ArtifactData(artifactInfo);
-
Either<ArtifactData, JanusGraphOperationStatus> existArtifact = janusGraphGenericDao
.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class);
if (existArtifact.isRight()) {
if (existArtifact.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
// create new node
- log.debug("Before adding artifact to graph {}" , artifactData);
- if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID().isEmpty())
+ log.debug("Before adding artifact to graph {}", artifactData);
+ if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID()
+ .isEmpty()) {
updateUUID(artifactData.getArtifactDataDefinition(), null, artifactData.getArtifactDataDefinition().getArtifactVersion());
- Either<ArtifactData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
- .createNode(artifactData, ArtifactData.class);
+ }
+ Either<ArtifactData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(artifactData, ArtifactData.class);
log.debug("After adding artifact to graph {}", artifactData);
-
if (createNodeResult.isRight()) {
JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
- log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(), operationStatus);
- BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus));
+ log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(),
+ operationStatus);
+ BeEcompErrorManager.getInstance()
+ .logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(),
+ String.valueOf(operationStatus));
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus));
}
artifactData = createNodeResult.left().value();
-
// add heat parameters
- if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
- StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef);
+ if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType()
+ .equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
+ StorageOperationStatus addPropertiesStatus = heatParametersOperation
+ .addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef);
if (addPropertiesStatus != StorageOperationStatus.OK) {
log.debug("Failed to create heat parameters on graph for artifact {}", artifactInfo.getArtifactName());
return Either.right(addPropertiesStatus);
}
}
-
} else {
log.debug("Failed to check existance of artifact in graph for id {}", artifactData.getUniqueId());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(existArtifact.right().value()));
}
} else if (failIfexist) {
log.debug("Artifact {} already exist", artifactData.getUniqueId());
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- JanusGraphOperationStatus.ALREADY_EXIST));
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ALREADY_EXIST));
} else {
artifactData = existArtifact.left().value();
}
-
UniqueIdData parent = new UniqueIdData(type, id);
-
// save logical artifact ref name on edge as property
Map<String, Object> properties = new HashMap<>();
properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), artifactInfo.getArtifactLabel());
- if (artifactInfo.getArtifactGroupType() != null)
+ if (artifactInfo.getArtifactGroupType() != null) {
properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), artifactInfo.getArtifactGroupType().getType());
+ }
Either<GraphRelation, JanusGraphOperationStatus> relation = janusGraphGenericDao
.createRelation(parent, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties);
if (relation.isRight()) {
log.debug("Failed to create relation in graph fro id {} to new artifact", id);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(relation.right().value()));
}
-
return Either.left(artifactData);
}
private boolean validateParentType(NodeTypeEnum type) {
boolean isValid = false;
switch (type) {
- case Resource:
- case InterfaceOperation:
- case Service:
- case ResourceInstance:
- isValid = true;
- break;
- default:
- log.debug("Not supported node type for artifact relation : {} ", type);
+ case Resource:
+ case InterfaceOperation:
+ case Service:
+ case ResourceInstance:
+ isValid = true;
+ break;
+ default:
+ log.debug("Not supported node type for artifact relation : {} ", type);
}
return isValid;
}
-
protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactData artifactDefResult) {
- log.debug("The object returned after create property is {}" ,artifactDefResult);
-
+ log.debug("The object returned after create property is {}", artifactDefResult);
ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult.getArtifactDataDefinition());
List<HeatParameterDefinition> parameters = new ArrayList<>();
- StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters);
+ StorageOperationStatus heatParametersOfNode = heatParametersOperation
+ .getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters);
if ((heatParametersOfNode.equals(StorageOperationStatus.OK)) && !parameters.isEmpty()) {
propertyDefResult.setListHeatParameters(parameters);
}
return propertyDefResult;
}
- public Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, boolean inTransaction) {
+ public Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId,
+ NodeTypeEnum type, boolean inTransaction) {
Either<ArtifactData, StorageOperationStatus> status = updateArtifactOnGraph(artifactInfo, artifactId, type, id);
-
if (status.isRight()) {
if (!inTransaction) {
janusGraphGenericDao.rollback();
@@ -215,22 +206,20 @@ public class ArtifactOperation {
janusGraphGenericDao.commit();
}
ArtifactData artifactData = status.left().value();
-
ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);
log.debug(THE_RETURNED_ARTIFACT_DEFINTION_IS, artifactDefResult);
return Either.left(artifactDefResult);
}
}
- public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact, boolean inTransaction) {
+ public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type,
+ boolean deleteMandatoryArtifact, boolean inTransaction) {
Either<ArtifactData, StorageOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact);
-
if (status.isRight()) {
if (!inTransaction) {
janusGraphGenericDao.rollback();
}
log.debug("Failed to delete artifact {} of resource {}", artifactId, id);
-
BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value()));
return Either.right(status.right().value());
} else {
@@ -238,34 +227,29 @@ public class ArtifactOperation {
janusGraphGenericDao.commit();
}
ArtifactData artifactData = status.left().value();
-
ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);
- log.debug(THE_RETURNED_ARTIFACT_DEFINTION_IS , artifactDefResult);
+ log.debug(THE_RETURNED_ARTIFACT_DEFINTION_IS, artifactDefResult);
return Either.left(artifactDefResult);
}
}
@SuppressWarnings("null")
- private Either<ArtifactData, StorageOperationStatus> updateArtifactOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id) {
-
+ private Either<ArtifactData, StorageOperationStatus> updateArtifactOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type,
+ String id) {
Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphGenericDao.getGraph();
if (graph.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graph.right().value()));
}
-
JanusGraph tGraph = graph.left().value();
-
- @SuppressWarnings("unchecked")
- Iterable<JanusGraphVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices();
+ @SuppressWarnings("unchecked") Iterable<JanusGraphVertex> verticesArtifact = tGraph.query()
+ .has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices();
Iterator<JanusGraphVertex> iterator = verticesArtifact.iterator();
if (!iterator.hasNext()) {
log.debug("No artifact node for id = {}", artifactId);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
JanusGraphVertex artifactV = iterator.next();
-
Iterator<Edge> iterEdge = artifactV.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.getProperty());
-
int edgeCount = 0;
Edge edgeFromTo = null;
while (iterEdge.hasNext()) {
@@ -277,17 +261,14 @@ public class ArtifactOperation {
}
++edgeCount;
}
-
if (isNeedUpdateHeatTime(artifactInfo)) {
artifactInfo.setHeatParamsUpdateDate(System.currentTimeMillis());
}
-
ArtifactData artifactData = new ArtifactData(artifactInfo);
if (edgeFromTo == null) {
log.debug("No relation between artifact = {} and node with id = {}", artifactId, id);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
-
Either<Boolean, StorageOperationStatus> setRelevantHeatParamIdRes = null;
if (edgeCount > 1) {
// need to remove relation, create new node
@@ -300,48 +281,49 @@ public class ArtifactOperation {
// update UUID and artifact version
String oldChecksum = artifactV.valueOrNull(
janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty()));
- String oldVersion = artifactV.valueOrNull(
- janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty()));
+ String oldVersion = artifactV
+ .valueOrNull(janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty()));
updateUUID(artifactInfo, oldChecksum, oldVersion);
log.debug("try to create new artifact ref node for id {}", uniqueId);
Either<ArtifactData, StorageOperationStatus> addedArtifactRes = addArtifactToGraph(artifactInfo, id, type, true);
-
if (addedArtifactRes.isLeft()) {
// remove all relations between groups to the old artifact
+
// add relation between the same groups to the new artifact
- StorageOperationStatus reassociateGroupsFromArtifact = groupOperation.dissociateAndAssociateGroupsFromArtifact(id, type, artifactId, addedArtifactRes.left().value(), true);
+ StorageOperationStatus reassociateGroupsFromArtifact = groupOperation
+ .dissociateAndAssociateGroupsFromArtifact(id, type, artifactId, addedArtifactRes.left().value(), true);
if (reassociateGroupsFromArtifact != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate groups to the new artifact", ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("UpdateArtifact", "Failed to reassociate groups to the new artifact", ErrorSeverity.ERROR);
return Either.right(reassociateGroupsFromArtifact);
}
-
- StorageOperationStatus reassociateGroupInstancesFromArtifact = groupInstanceOperation.dissociateAndAssociateGroupsInstanceFromArtifact(id, type, artifactId, addedArtifactRes.left().value());
+ StorageOperationStatus reassociateGroupInstancesFromArtifact = groupInstanceOperation
+ .dissociateAndAssociateGroupsInstanceFromArtifact(id, type, artifactId, addedArtifactRes.left().value());
if (reassociateGroupInstancesFromArtifact != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate group instances to the new artifact", ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("UpdateArtifact", "Failed to reassociate group instances to the new artifact", ErrorSeverity.ERROR);
return Either.right(reassociateGroupsFromArtifact);
}
-
// If artifact is heat env
if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
ArtifactData addedArtifact = addedArtifactRes.left().value();
String newArtifactUniqueId = addedArtifact.getUniqueId();
Either<HeatParameterValueData, StorageOperationStatus> updateResult = null;
-
setRelevantHeatParamIdRes = setRelevantHeatParamId(artifactV, artifactInfo);
if (setRelevantHeatParamIdRes.isRight()) {
- log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value());
+ log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(),
+ setRelevantHeatParamIdRes.right().value());
return Either.right(setRelevantHeatParamIdRes.right().value());
}
for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) {
- updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, newArtifactUniqueId, id, artifactInfo.getArtifactLabel());
+ updateResult = heatParametersOperation
+ .updateHeatParameterValue(heatEnvParam, newArtifactUniqueId, id, artifactInfo.getArtifactLabel());
if (updateResult.isRight()) {
log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value());
return Either.right(updateResult.right().value());
}
}
-
Iterator<Edge> iterEdgeGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty());
-
if (!iterEdgeGeneratedFrom.hasNext()) {
log.error("No heat artifact node for id = {}", artifactId);
return Either.right(StorageOperationStatus.NOT_FOUND);
@@ -354,12 +336,12 @@ public class ArtifactOperation {
.createRelation(addedArtifact, generatedFromArtifactNode, GraphEdgeLabels.GENERATED_FROM, null);
if (createRelationToGeneratedFromArtifactRes.isRight()) {
log.error("Failed to create relation from heat_env {} to heat {}", addedArtifact.getUniqueId(), generatedFromArtifactNode);
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createRelationToGeneratedFromArtifactRes.right().value()));
+ return Either.right(
+ DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createRelationToGeneratedFromArtifactRes.right().value()));
}
}
}
return addedArtifactRes;
-
} else {
if (edgeCount == 1) {
String oldChecksum = artifactV.valueOrNull(
@@ -368,23 +350,23 @@ public class ArtifactOperation {
janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty()));
updateUUID(artifactInfo, oldChecksum, oldVersion);
// update exist
- Either<ArtifactData, JanusGraphOperationStatus> updatedArtifact = janusGraphGenericDao
- .updateNode(artifactData, ArtifactData.class);
+ Either<ArtifactData, JanusGraphOperationStatus> updatedArtifact = janusGraphGenericDao.updateNode(artifactData, ArtifactData.class);
if (updatedArtifact.isRight()) {
log.debug("failed to update artifact node for id {}", artifactData.getUniqueId());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updatedArtifact.right().value()));
}
-
if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
Either<HeatParameterValueData, StorageOperationStatus> updateResult = null;
String artifactUniqueId = artifactInfo.getUniqueId();
setRelevantHeatParamIdRes = setRelevantHeatParamId(artifactV, artifactInfo);
if (setRelevantHeatParamIdRes.isRight()) {
- log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value());
+ log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(),
+ setRelevantHeatParamIdRes.right().value());
return Either.right(setRelevantHeatParamIdRes.right().value());
}
for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) {
- updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, artifactUniqueId, id, artifactInfo.getArtifactLabel());
+ updateResult = heatParametersOperation
+ .updateHeatParameterValue(heatEnvParam, artifactUniqueId, id, artifactInfo.getArtifactLabel());
if (updateResult.isRight()) {
log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value());
return Either.right(updateResult.right().value());
@@ -394,27 +376,27 @@ public class ArtifactOperation {
if (artifactData.getArtifactDataDefinition().getArtifactChecksum() == null) {
// update heat parameters only if it is not heat env
if (artifactInfo.getGeneratedFromId() == null) {
- StorageOperationStatus operationStatus = heatParametersOperation.updateHeatParameters(artifactInfo.getListHeatParameters());
+ StorageOperationStatus operationStatus = heatParametersOperation
+ .updateHeatParameters(artifactInfo.getListHeatParameters());
if (operationStatus != StorageOperationStatus.OK) {
return Either.right(operationStatus);
}
}
} else {
- Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteParameters = heatParametersOperation.deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactInfo.getUniqueId());
+ Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteParameters = heatParametersOperation
+ .deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactInfo.getUniqueId());
if (deleteParameters.isRight()) {
log.debug("failed to update heat parameters for artifact id {}", artifactData.getUniqueId());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
-
- StorageOperationStatus addParameters = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactId, NodeTypeEnum.ArtifactRef);
+ StorageOperationStatus addParameters = heatParametersOperation
+ .addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactId, NodeTypeEnum.ArtifactRef);
if (!addParameters.equals(StorageOperationStatus.OK)) {
log.debug("failed to update heat parameters for artifact id {}", artifactData.getUniqueId());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
-
}
}
-
return Either.left(updatedArtifact.left().value());
} else {
log.debug("No relevent edges for artifact = {}", artifactId);
@@ -424,25 +406,23 @@ public class ArtifactOperation {
}
private boolean isNeedUpdateHeatTime(ArtifactDefinition artifactInfo) {
- if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType())) {
+ if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || artifactInfo.getArtifactType()
+ .equals(ArtifactTypeEnum.HEAT_NET.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType())) {
return true;
}
return false;
}
private Either<Boolean, StorageOperationStatus> setRelevantHeatParamId(JanusGraphVertex artifactV, ArtifactDefinition artifactInfo) {
-
Map<String, String> heatParametersHM = new HashMap<>();
-
Iterator<Edge> iterHeat = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty());
if (!iterHeat.hasNext()) {
- log.debug("No edges with label GENERATED_FROM for the node {}" , artifactInfo.getUniqueId());
+ log.debug("No edges with label GENERATED_FROM for the node {}", artifactInfo.getUniqueId());
return Either.right(StorageOperationStatus.NOT_FOUND);
}
Edge heat = iterHeat.next();
Vertex heatVertex = heat.inVertex();
String heatUniqueId = (String) heatVertex.value(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef));
-
Either<List<ImmutablePair<HeatParameterData, GraphEdge>>, JanusGraphOperationStatus> getHeatParametersRes = janusGraphGenericDao
.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatUniqueId, GraphEdgeLabels.HEAT_PARAMETER,
NodeTypeEnum.HeatParameter, HeatParameterData.class);
@@ -469,19 +449,17 @@ public class ArtifactOperation {
return Either.left(true);
}
- private Either<ArtifactData, StorageOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
- Either<JanusGraph, StorageOperationStatus> graph = janusGraphGenericDao.getGraph()
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ private Either<ArtifactData, StorageOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type,
+ boolean deleteMandatoryArtifact) {
+ Either<JanusGraph, StorageOperationStatus> graph = janusGraphGenericDao.getGraph().right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (graph.isRight()) {
return Either.right(graph.right().value());
}
-
JanusGraph tGraph = graph.left().value();
Either<ArtifactData, StorageOperationStatus> artifactData = janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (artifactData.isRight()) {
log.debug("Failed to retrieve artifact for id = {}", artifactId);
return Either.right(artifactData.right().value());
@@ -491,9 +469,8 @@ public class ArtifactOperation {
if ((artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) && !deleteMandatoryArtifact) {
isMandatory = true;
}
-
- @SuppressWarnings("unchecked")
- Iterable<JanusGraphVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices();
+ @SuppressWarnings("unchecked") Iterable<JanusGraphVertex> verticesArtifact = tGraph.query()
+ .has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices();
Iterator<JanusGraphVertex> iterator = verticesArtifact.iterator();
if (!iterator.hasNext()) {
log.debug("No artifact node for id = {}", artifactId);
@@ -516,35 +493,35 @@ public class ArtifactOperation {
log.debug("No relation between artifact = {} and node with id = {}", artifactId, id);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
-
// need to remove relation from resource/interface
-
log.debug("remove edge {}", edgeFromTo);
if (!isMandatory || (isMandatory && edgeCount > 1)) {
edgeFromTo.remove();
}
-
// delete edges from all groups under the component id which related to
+
// this artifact.
+
// Also in case it is a mandatory artifact.
- Either<List<GraphRelation>, StorageOperationStatus> dissociateAllGroups = groupOperation.dissociateAllGroupsFromArtifactOnGraph(id, type, artifactId);
+ Either<List<GraphRelation>, StorageOperationStatus> dissociateAllGroups = groupOperation
+ .dissociateAllGroupsFromArtifactOnGraph(id, type, artifactId);
if (dissociateAllGroups.isRight()) {
StorageOperationStatus status = dissociateAllGroups.right().value();
if (status != StorageOperationStatus.NOT_FOUND && status != StorageOperationStatus.OK) {
return Either.right(status);
}
}
-
if (edgeCount == 1) {
// remove artifactRef node
log.debug("Remove artifactRef node from graph");
- Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteStatus = heatParametersOperation.deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId);
+ Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteStatus = heatParametersOperation
+ .deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId);
if (deleteStatus.isRight()) {
log.error("failed to delete heat parameters of artifact {}", artifactId);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
-
- StorageOperationStatus deleteValuesStatus = heatParametersOperation.deleteAllHeatValuesAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId);
+ StorageOperationStatus deleteValuesStatus = heatParametersOperation
+ .deleteAllHeatValuesAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId);
if (!deleteValuesStatus.equals(StorageOperationStatus.OK)) {
log.error("failed to delete heat values of artifact {}", artifactId);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
@@ -555,19 +532,17 @@ public class ArtifactOperation {
} else {
log.debug("artifactRef have more connection. ArtifactRef node will not be removed ");
}
-
return Either.left(artifactData.left().value());
-
}
/**
- *
* @param parentId
* @param parentType
* @param inTransaction
* @return
*/
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction) {
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType,
+ boolean inTransaction) {
Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = null;
try {
Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphGenericDao.getGraph();
@@ -576,31 +551,26 @@ public class ArtifactOperation {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graph.right().value()));
}
JanusGraph tGraph = graph.left().value();
- @SuppressWarnings("unchecked")
- Iterable<JanusGraphVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices();
+ @SuppressWarnings("unchecked") Iterable<JanusGraphVertex> vertices = tGraph.query()
+ .has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices();
if (vertices == null) {
log.debug("No nodes for type {} for id = {}", parentType, parentId);
result = Either.right(StorageOperationStatus.NOT_FOUND);
return result;
}
Iterator<JanusGraphVertex> iterator = vertices.iterator();
-
Map<String, ArtifactDefinition> artifactMap = new HashMap<>();
while (iterator.hasNext()) {
Vertex vertex = iterator.next();
Iterator<Edge> iteratorEdge = vertex.edges(Direction.OUT, GraphEdgeLabels.ARTIFACT_REF.getProperty());
-
if (iteratorEdge != null) {
-
while (iteratorEdge.hasNext()) {
Edge edge = iteratorEdge.next();
-
Vertex artifactV = edge.inVertex();
-
Map<String, Object> properties = this.janusGraphGenericDao.getProperties(artifactV);
- ArtifactData artifact = GraphElementFactory.createElement(NodeTypeEnum.ArtifactRef.getName(), GraphElementTypeEnum.Node, properties, ArtifactData.class);
+ ArtifactData artifact = GraphElementFactory
+ .createElement(NodeTypeEnum.ArtifactRef.getName(), GraphElementTypeEnum.Node, properties, ArtifactData.class);
if (artifact != null) {
-
ArtifactDefinition artifactDefinition = new ArtifactDefinition(artifact.getArtifactDataDefinition());
Iterator<Edge> edgesGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty());
if (edgesGeneratedFrom != null && edgesGeneratedFrom.hasNext()) {
@@ -610,7 +580,8 @@ public class ArtifactOperation {
artifactDefinition.setGeneratedFromId(artifactIdGeneratedFrom);
}
List<HeatParameterDefinition> heatParams = new ArrayList<>();
- StorageOperationStatus heatParametersStatus = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId(), heatParams);
+ StorageOperationStatus heatParametersStatus = heatParametersOperation
+ .getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId(), heatParams);
if (!heatParametersStatus.equals(StorageOperationStatus.OK)) {
log.debug("failed to get heat parameters for node {} {}", parentType.getName(), parentId);
return Either.right(heatParametersStatus);
@@ -633,16 +604,14 @@ public class ArtifactOperation {
} else {
this.janusGraphGenericDao.commit();
}
-
}
}
-
}
private void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) {
- if (oldVesrion == null || oldVesrion.isEmpty())
+ if (oldVesrion == null || oldVesrion.isEmpty()) {
oldVesrion = "0";
-
+ }
String currentChecksum = artifactData.getArtifactChecksum();
if (oldChecksum == null || oldChecksum.isEmpty()) {
if (currentChecksum != null) {
@@ -651,11 +620,9 @@ public class ArtifactOperation {
} else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) {
generateUUID(artifactData, oldVesrion);
}
-
}
private void generateUUID(ArtifactDataDefinition artifactData, String oldVesrion) {
-
UUID uuid = UUID.randomUUID();
artifactData.setArtifactUUID(uuid.toString());
MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, uuid.toString());
@@ -669,5 +636,4 @@ public class ArtifactOperation {
newVersion++;
artifactData.setArtifactVersion(String.valueOf(newVersion));
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java
index 0bbaa0ecb2..0adb90de80 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java
@@ -17,7 +17,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
import com.google.gson.JsonElement;
@@ -49,16 +48,13 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
@Component("attribute-operation")
public class AttributeOperation extends AbstractOperation {
- private static Logger log = Logger.getLogger(AttributeOperation.class.getName());
-
private static final String FAILED_TO_FETCH_ATTRIBUTES_OF_DATA_TYPE = "Failed to fetch attributes of data type {}";
private static final String DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS = "Data type {} cannot be found in graph. status is {}";
private static final String THE_VALUE_OF_ATTRIBUTE_FROM_TYPE_IS_INVALID = "The value {} of attribute from type {} is invalid";
-
+ private static Logger log = Logger.getLogger(AttributeOperation.class.getName());
@Autowired
public AttributeOperation(HealingJanusGraphGenericDao janusGraphGenericDao) {
@@ -66,28 +62,22 @@ public class AttributeOperation extends AbstractOperation {
}
public boolean isAttributeTypeValid(final AttributeDataDefinition attributeDefinition) {
-
if (attributeDefinition == null) {
return false;
}
-
if (ToscaPropertyType.isValidType(attributeDefinition.getType()) == null) {
- final Either<Boolean, JanusGraphOperationStatus> definedInDataTypes = isDefinedInDataTypes(
- attributeDefinition.getType());
-
+ final Either<Boolean, JanusGraphOperationStatus> definedInDataTypes = isDefinedInDataTypes(attributeDefinition.getType());
if (definedInDataTypes.isRight()) {
return false;
} else {
Boolean isExist = definedInDataTypes.left().value();
return isExist.booleanValue();
}
-
}
return true;
}
public Either<Boolean, JanusGraphOperationStatus> isDefinedInDataTypes(final String propertyType) {
-
final String dataTypeUid = UniqueIdBuilder.buildDataTypeUid(propertyType);
final Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(dataTypeUid);
if (dataTypeByUid.isRight()) {
@@ -97,44 +87,35 @@ public class AttributeOperation extends AbstractOperation {
}
return Either.right(status);
}
-
return Either.left(true);
-
}
/**
* Build Data type object from graph by unique id
*/
public Either<DataTypeDefinition, JanusGraphOperationStatus> getDataTypeByUid(final String uniqueId) {
-
final Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
-
if (dataTypesRes.isRight()) {
JanusGraphOperationStatus status = dataTypesRes.right().value();
log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
return Either.right(status);
}
-
final DataTypeData ctData = dataTypesRes.left().value();
final DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
-
final JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
if (propertiesStatus != JanusGraphOperationStatus.OK) {
log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, FAILED_TO_FETCH_ATTRIBUTES_OF_DATA_TYPE, uniqueId);
return Either.right(propertiesStatus);
}
-
final Either<ImmutablePair<DataTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM,
- NodeTypeEnum.DataType,
+ .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
DataTypeData.class);
log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode);
if (parentNode.isRight()) {
final JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
- log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR,
- "Failed to find the parent data type of data type {}. status is {}", uniqueId,
+ log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, "Failed to find the parent data type of data type {}. status is {}", uniqueId,
janusGraphOperationStatus);
return Either.right(janusGraphOperationStatus);
}
@@ -142,32 +123,23 @@ public class AttributeOperation extends AbstractOperation {
// derived from node was found
final ImmutablePair<DataTypeData, GraphEdge> immutablePair = parentNode.left().value();
final DataTypeData parentCT = immutablePair.getKey();
-
final String parentUniqueId = parentCT.getUniqueId();
- final Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(
- parentUniqueId);
-
+ final Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(parentUniqueId);
if (dataTypeByUid.isRight()) {
return Either.right(dataTypeByUid.right().value());
}
-
final DataTypeDefinition parentDataTypeDefinition = dataTypeByUid.left().value();
-
dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
}
-
return Either.left(dataTypeDefinition);
}
- private JanusGraphOperationStatus fillProperties(final String uniqueId,
- final DataTypeDefinition dataTypeDefinition) {
-
+ private JanusGraphOperationStatus fillProperties(final String uniqueId, final DataTypeDefinition dataTypeDefinition) {
final Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode = this
.findPropertiesOfNode(NodeTypeEnum.DataType, uniqueId);
if (findPropertiesOfNode.isRight()) {
final JanusGraphOperationStatus janusGraphOperationStatus = findPropertiesOfNode.right().value();
- log.debug("After looking for properties of vertex {}. status is {}", uniqueId,
- janusGraphOperationStatus);
+ log.debug("After looking for properties of vertex {}. status is {}", uniqueId, janusGraphOperationStatus);
if (JanusGraphOperationStatus.NOT_FOUND.equals(janusGraphOperationStatus)) {
return JanusGraphOperationStatus.OK;
} else {
@@ -177,7 +149,6 @@ public class AttributeOperation extends AbstractOperation {
final Map<String, PropertyDefinition> properties = findPropertiesOfNode.left().value();
if (properties != null && !properties.isEmpty()) {
List<PropertyDefinition> listOfProps = new ArrayList<>();
-
for (final Entry<String, PropertyDefinition> entry : properties.entrySet()) {
final String propName = entry.getKey();
final PropertyDefinition propertyDefinition = entry.getValue();
@@ -191,21 +162,16 @@ public class AttributeOperation extends AbstractOperation {
}
}
- public Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode(
- final NodeTypeEnum nodeType, final String uniqueId) {
-
+ public Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode(final NodeTypeEnum nodeType,
+ final String uniqueId) {
final Map<String, PropertyDefinition> resourceProps = new HashMap<>();
-
final Either<List<ImmutablePair<PropertyData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.PROPERTY,
- NodeTypeEnum.Property,
+ .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property,
PropertyData.class);
-
if (childrenNodes.isRight()) {
final JanusGraphOperationStatus operationStatus = childrenNodes.right().value();
return Either.right(operationStatus);
}
-
final List<ImmutablePair<PropertyData, GraphEdge>> values = childrenNodes.left().value();
if (values != null) {
for (final ImmutablePair<PropertyData, GraphEdge> immutablePair : values) {
@@ -213,61 +179,47 @@ public class AttributeOperation extends AbstractOperation {
final String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
log.debug("Attribute {} is associated to node {}", propertyName, uniqueId);
final PropertyData propertyData = immutablePair.getKey();
- final PropertyDefinition propertyDefinition = this
- .convertPropertyDataToPropertyDefinition(propertyData, propertyName);
+ final PropertyDefinition propertyDefinition = this.convertPropertyDataToPropertyDefinition(propertyData, propertyName);
resourceProps.put(propertyName, propertyDefinition);
}
-
}
-
log.debug("The properties associated to node {} are {}", uniqueId, resourceProps);
return Either.left(resourceProps);
}
- public PropertyDefinition convertPropertyDataToPropertyDefinition(final PropertyData propertyDataResult,
- final String propertyName) {
+ public PropertyDefinition convertPropertyDataToPropertyDefinition(final PropertyData propertyDataResult, final String propertyName) {
log.debug("The object returned after create property is {}", propertyDataResult);
-
final PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition());
propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints()));
propertyDefResult.setName(propertyName);
-
return propertyDefResult;
}
-
public ImmutablePair<String, Boolean> isAttributeInnerTypeValid(final AttributeDataDefinition attributeDefinition,
final Map<String, DataTypeDefinition> dataTypes) {
-
if (attributeDefinition == null) {
return new ImmutablePair<>(null, false);
}
-
SchemaDefinition schema;
PropertyDataDefinition innerProp;
String innerType = null;
if ((schema = attributeDefinition.getSchema()) != null && ((innerProp = schema.getProperty()) != null)) {
innerType = innerProp.getType();
}
-
final ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
-
if (innerToscaType == null) {
final DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
if (dataTypeDefinition == null) {
log.debug("The inner type {} is not a data type.", innerType);
return new ImmutablePair<>(innerType, false);
} else {
- log.debug("The inner type {} is a data type. Data type definition is {}", innerType,
- dataTypeDefinition);
+ log.debug("The inner type {} is a data type. Data type definition is {}", innerType, dataTypeDefinition);
}
}
return new ImmutablePair<>(innerType, true);
}
-
- public boolean isAttributeDefaultValueValid(final AttributeDataDefinition attributeDefinition,
- final Map<String, DataTypeDefinition> dataTypes) {
+ public boolean isAttributeDefaultValueValid(final AttributeDataDefinition attributeDefinition, final Map<String, DataTypeDefinition> dataTypes) {
if (attributeDefinition == null) {
return false;
}
@@ -291,7 +243,6 @@ public class AttributeOperation extends AbstractOperation {
isValid = isValidValue(type, value, innerType, dataTypes);
} else {
log.trace("The given type {} is not a pre defined one.", propertyType);
-
final DataTypeDefinition foundDt = dataTypes.get(propertyType);
if (foundDt != null) {
isValid = isValidComplexValue(foundDt, value, dataTypes);
@@ -302,60 +253,40 @@ public class AttributeOperation extends AbstractOperation {
return isValid;
}
- private boolean isValidComplexValue(final DataTypeDefinition foundDt, final String value,
- final Map<String, DataTypeDefinition> dataTypes) {
- final ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter
- .validateAndUpdate(value, foundDt, dataTypes);
-
+ private boolean isValidComplexValue(final DataTypeDefinition foundDt, final String value, final Map<String, DataTypeDefinition> dataTypes) {
+ final ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter.validateAndUpdate(value, foundDt, dataTypes);
log.trace("The result after validating complex value of type {} is {}", foundDt.getName(), validateAndUpdate);
-
return validateAndUpdate.right.booleanValue();
-
}
-
public StorageOperationStatus validateAndUpdateAttribute(final AttributeDataDefinition attributeDefinition,
final Map<String, DataTypeDefinition> dataTypes) {
-
log.trace("Going to validate attribute type and value. {}", attributeDefinition);
-
final String attributeDefinitionType = attributeDefinition.getType();
final String value = (String) attributeDefinition.get_default();
-
final ToscaPropertyType type = getType(attributeDefinitionType);
-
if (type == null) {
-
final DataTypeDefinition dataTypeDefinition = dataTypes.get(attributeDefinitionType);
if (dataTypeDefinition == null) {
log.debug("The type {} of attribute cannot be found.", attributeDefinitionType);
return StorageOperationStatus.INVALID_TYPE;
}
-
- return validateAndUpdateAttributeComplexValue(attributeDefinition, attributeDefinitionType, value,
- dataTypeDefinition, dataTypes);
-
+ return validateAndUpdateAttributeComplexValue(attributeDefinition, attributeDefinitionType, value, dataTypeDefinition, dataTypes);
}
String innerType;
-
final Either<String, JanusGraphOperationStatus> checkInnerType = getInnerType(type, attributeDefinition::getSchema);
if (checkInnerType.isRight()) {
return StorageOperationStatus.INVALID_TYPE;
}
innerType = checkInnerType.left().value();
-
log.trace("After validating property type {}", attributeDefinitionType);
-
if (!isValidValue(type, value, innerType, dataTypes)) {
log.info(THE_VALUE_OF_ATTRIBUTE_FROM_TYPE_IS_INVALID, value, type);
return StorageOperationStatus.INVALID_VALUE;
}
-
final PropertyValueConverter converter = type.getConverter();
-
if (isEmptyValue(value)) {
- log.debug("Default value was not sent for attribute {}. Set default value to {}",
- attributeDefinition.getName(), EMPTY_VALUE);
+ log.debug("Default value was not sent for attribute {}. Set default value to {}", attributeDefinition.getName(), EMPTY_VALUE);
attributeDefinition.set_default(EMPTY_VALUE);
} else if (!isEmptyValue(value)) {
attributeDefinition.set_default(converter.convert(value, innerType, dataTypes));
@@ -363,15 +294,11 @@ public class AttributeOperation extends AbstractOperation {
return StorageOperationStatus.OK;
}
- private StorageOperationStatus validateAndUpdateAttributeComplexValue(
- final AttributeDataDefinition attributeDefinition,
- final String attributeType,
- final String value,
- final DataTypeDefinition dataTypeDefinition,
- final Map<String, DataTypeDefinition> dataTypes) {
-
- final ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter
- .validateAndUpdate(value, dataTypeDefinition, dataTypes);
+ private StorageOperationStatus validateAndUpdateAttributeComplexValue(final AttributeDataDefinition attributeDefinition,
+ final String attributeType, final String value,
+ final DataTypeDefinition dataTypeDefinition,
+ final Map<String, DataTypeDefinition> dataTypes) {
+ final ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
if (!validateResult.right.booleanValue()) {
log.debug(THE_VALUE_OF_ATTRIBUTE_FROM_TYPE_IS_INVALID, attributeType, attributeType);
return StorageOperationStatus.INVALID_VALUE;
@@ -385,8 +312,7 @@ public class AttributeOperation extends AbstractOperation {
return StorageOperationStatus.OK;
}
- private void updateAttributeValue(final AttributeDataDefinition attributeDefinition,
- final JsonElement jsonElement) {
+ private void updateAttributeValue(final AttributeDataDefinition attributeDefinition, final JsonElement jsonElement) {
attributeDefinition.set_default(jsonElement);
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java
index 9ee085342e..5787c5b3b8 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import static org.springframework.util.CollectionUtils.isEmpty;
@@ -55,150 +54,113 @@ import org.springframework.stereotype.Component;
@Component("capability-operation")
public class CapabilityOperation extends AbstractOperation {
-
private static final Logger log = Logger.getLogger(CapabilityOperation.class.getName());
-
private final CapabilityTypeOperation capabilityTypeOperation;
private final PropertyOperation propertyOperation;
-
public CapabilityOperation(CapabilityTypeOperation capabilityTypeOperation, PropertyOperation propertyOperation) {
this.capabilityTypeOperation = capabilityTypeOperation;
this.propertyOperation = propertyOperation;
}
-
- public Either<CapabilityData, JanusGraphOperationStatus> addCapabilityToGraph(String resourceId, CapabilityTypeData capTypeData, CapabilityDefinition capabilityDefinition) {
-
+ public Either<CapabilityData, JanusGraphOperationStatus> addCapabilityToGraph(String resourceId, CapabilityTypeData capTypeData,
+ CapabilityDefinition capabilityDefinition) {
log.debug("#addCapabilityToGraph - capabilityDefinition={}", capabilityDefinition);
-
String capUniqueId = UniqueIdBuilder.buildCapabilityUid(resourceId, capabilityDefinition.getName());
CapabilityData capabilityData = buildCapabilityData(capabilityDefinition, capUniqueId);
-
log.debug("addCapabilityToGraph - Before adding capability to graph. capabilityTypeData = {}", capabilityData);
- Either<CapabilityData, JanusGraphOperationStatus> createCapResult = janusGraphGenericDao
- .createNode(capabilityData, CapabilityData.class);
+ Either<CapabilityData, JanusGraphOperationStatus> createCapResult = janusGraphGenericDao.createNode(capabilityData, CapabilityData.class);
log.debug("addCapabilityToGraph - After adding capability to graph. status is = {}", createCapResult);
-
if (createCapResult.isRight()) {
JanusGraphOperationStatus operationStatus = createCapResult.right().value();
- log.error("addCapabilityToGraph - Failed to add capability of type {} to graph. status is {}", capabilityDefinition.getType(), operationStatus);
+ log.error("addCapabilityToGraph - Failed to add capability of type {} to graph. status is {}", capabilityDefinition.getType(),
+ operationStatus);
return createCapResult;
}
-
- createCapResult = connectToCapabilityType(capabilityData, capTypeData)
- .left()
- .bind(res -> createCapabilityProperties(capabilityData, capTypeData))
- .left()
- .map(res -> capabilityData);
-
+ createCapResult = connectToCapabilityType(capabilityData, capTypeData).left()
+ .bind(res -> createCapabilityProperties(capabilityData, capTypeData)).left().map(res -> capabilityData);
return createCapResult;
}
-
- private Either<GraphRelation, JanusGraphOperationStatus> connectToCapabilityType(CapabilityData capabilityData, CapabilityTypeData capabilityTypeData) {
-
- Map<String, Object> properties = new HashMap<>();
+ private Either<GraphRelation, JanusGraphOperationStatus> connectToCapabilityType(CapabilityData capabilityData,
+ CapabilityTypeData capabilityTypeData) {
+ Map<String, Object> properties = new HashMap<>();
String capabilityName = capabilityData.getCapabilityDataDefinition().getName();
properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName);
-
- return janusGraphGenericDao
- .createRelation(capabilityData, capabilityTypeData, GraphEdgeLabels.CAPABILITY_IMPL, properties);
-
+ return janusGraphGenericDao.createRelation(capabilityData, capabilityTypeData, GraphEdgeLabels.CAPABILITY_IMPL, properties);
}
-
/**
* @param capabilites
* @return
*/
- public Either<List<CapabilityDefinition>, JanusGraphOperationStatus> getCapabilitiesWithProps(List<ImmutablePair<CapabilityData, GraphEdge>> capabilites) {
- List<Either<CapabilityDefinition, JanusGraphOperationStatus>> listFilledCapabilitiesResults = capabilites.stream()
- .map(ImmutablePair::getLeft)
- .map(this::toCapabilityDefinitionWithProps)
- .collect(Collectors.toList());
-
- Optional<JanusGraphOperationStatus> status = listFilledCapabilitiesResults.stream().filter(Either::isRight)
- .map(res -> res.right().value())
- .findFirst();
-
+ public Either<List<CapabilityDefinition>, JanusGraphOperationStatus> getCapabilitiesWithProps(
+ List<ImmutablePair<CapabilityData, GraphEdge>> capabilites) {
+ List<Either<CapabilityDefinition, JanusGraphOperationStatus>> listFilledCapabilitiesResults = capabilites.stream().map(ImmutablePair::getLeft)
+ .map(this::toCapabilityDefinitionWithProps).collect(Collectors.toList());
+ Optional<JanusGraphOperationStatus> status = listFilledCapabilitiesResults.stream().filter(Either::isRight).map(res -> res.right().value())
+ .findFirst();
if (status.isPresent()) {
return Either.right(status.get());
}
-
- List<CapabilityDefinition> listCapabilities = listFilledCapabilitiesResults.stream()
- .map(res -> res.left().value())
- .collect(Collectors.toList());
-
+ List<CapabilityDefinition> listCapabilities = listFilledCapabilitiesResults.stream().map(res -> res.left().value())
+ .collect(Collectors.toList());
return Either.left(listCapabilities);
}
-
+
private Either<CapabilityDefinition, JanusGraphOperationStatus> toCapabilityDefinitionWithProps(CapabilityData capabilityData) {
CapabilityDefinition capabilityDefinition = new CapabilityDefinition(capabilityData.getCapabilityDataDefinition());
- return getCapabilityProperties(capabilityDefinition.getUniqueId(), capabilityDefinition.getType())
- .left()
- .map(props -> {
- capabilityDefinition.setProperties(props);
- return capabilityDefinition;
- });
+ return getCapabilityProperties(capabilityDefinition.getUniqueId(), capabilityDefinition.getType()).left().map(props -> {
+ capabilityDefinition.setProperties(props);
+ return capabilityDefinition;
+ });
}
-
-
+
/**
* get all properties of the capability.
- *
+ * <p>
* the property definition is taken from the capability type.
*
* @param capabilityUid
* @return
*/
private Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getCapabilityProperties(String capabilityUid, String capabilityType) {
- Either<CapabilityTypeDefinition, JanusGraphOperationStatus> capabilityTypeRes = capabilityTypeOperation.getCapabilityTypeByType(capabilityType);
-
+ Either<CapabilityTypeDefinition, JanusGraphOperationStatus> capabilityTypeRes = capabilityTypeOperation
+ .getCapabilityTypeByType(capabilityType);
if (capabilityTypeRes.isRight()) {
JanusGraphOperationStatus status = capabilityTypeRes.right().value();
return Either.right(status);
}
-
CapabilityTypeDefinition capabilityTypeDefinition = capabilityTypeRes.left().value();
-
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> typesPropsRes = getPropertiesOfCapabilityTypeAndAcestors(capabilityTypeDefinition);
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> typesPropsRes = getPropertiesOfCapabilityTypeAndAcestors(
+ capabilityTypeDefinition);
if (typesPropsRes.isRight()) {
JanusGraphOperationStatus status = typesPropsRes.right().value();
return Either.right(status);
}
-
Map<String, PropertyDefinition> capabilityTypeProperties = typesPropsRes.left().value();
-
if (isEmpty(capabilityTypeProperties)) {
return Either.right(JanusGraphOperationStatus.OK);
}
-
Map<String, PropertyDefinition> uidToPropDefMap = capabilityTypeProperties.values().stream()
- .collect(Collectors.toMap(PropertyDefinition::getUniqueId, Function.identity()));
-
+ .collect(Collectors.toMap(PropertyDefinition::getUniqueId, Function.identity()));
// Find all properties values on the capability
Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, JanusGraphOperationStatus> propertyValNodes = janusGraphGenericDao
.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, GraphEdgeLabels.PROPERTY_VALUE,
NodeTypeEnum.PropertyValue, PropertyValueData.class);
-
if (propertyValNodes.isRight()) {
return onLoadPropValuesFailure(propertyValNodes.right().value(), capabilityTypeProperties);
}
-
List<ImmutablePair<PropertyValueData, GraphEdge>> propValsRelationPairs = propertyValNodes.left().value();
if (isEmpty(propValsRelationPairs)) {
return Either.right(JanusGraphOperationStatus.OK);
}
-
List<ComponentInstanceProperty> capabilityProperties = new ArrayList<>();
-
for (ImmutablePair<PropertyValueData, GraphEdge> propValRelPair : propValsRelationPairs) {
-
PropertyValueData propertyValueData = propValRelPair.getLeft();
Either<ImmutablePair<PropertyData, GraphEdge>, JanusGraphOperationStatus> propertyDefRes = janusGraphGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueData.getUniqueId(), GraphEdgeLabels.PROPERTY_IMPL,
- NodeTypeEnum.Property, PropertyData.class);
+ .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueData.getUniqueId(),
+ GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class);
if (propertyDefRes.isRight()) {
JanusGraphOperationStatus status = propertyDefRes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -206,40 +168,33 @@ public class CapabilityOperation extends AbstractOperation {
}
return Either.right(status);
}
-
ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value();
PropertyData propertyData = propertyDefPair.left;
String propertyUniqueId = propertyData.getPropertyDataDefinition().getUniqueId();
-
PropertyDefinition propertyDefinition = uidToPropDefMap.get(propertyUniqueId);
- ComponentInstanceProperty capabilityProperty = new ComponentInstanceProperty(propertyDefinition, propertyValueData.getValue(), propertyValueData.getUniqueId());
-
+ ComponentInstanceProperty capabilityProperty = new ComponentInstanceProperty(propertyDefinition, propertyValueData.getValue(),
+ propertyValueData.getUniqueId());
capabilityProperties.add(capabilityProperty);
}
-
Set<String> processedProps = buildProcessedPropsSet(capabilityProperties);
-
// Find all properties which does not have property value on the group.
List<ComponentInstanceProperty> leftProps = filterCapabilityTypesProps(capabilityTypeProperties, processedProps);
if (leftProps != null) {
capabilityProperties.addAll(leftProps);
}
-
return Either.left(capabilityProperties);
}
-
/**
* @param capabilityProperties
* @return
*/
private Set<String> buildProcessedPropsSet(List<ComponentInstanceProperty> capabilityProperties) {
- return capabilityProperties.stream()
- .map(ComponentInstanceProperty::getName)
- .collect(Collectors.toSet());
+ return capabilityProperties.stream().map(ComponentInstanceProperty::getName).collect(Collectors.toSet());
}
-
- private Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> onLoadPropValuesFailure(JanusGraphOperationStatus status, Map<String, PropertyDefinition> capabilityTypeProperties) {
+
+ private Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> onLoadPropValuesFailure(JanusGraphOperationStatus status,
+ Map<String, PropertyDefinition> capabilityTypeProperties) {
if (status == JanusGraphOperationStatus.NOT_FOUND) {
return Either.left(buildPropsFromCapabilityTypeProps(capabilityTypeProperties));
} else {
@@ -247,31 +202,29 @@ public class CapabilityOperation extends AbstractOperation {
}
}
-
/**
* @param capabilityTypeProperties
* @return
*/
private List<ComponentInstanceProperty> buildPropsFromCapabilityTypeProps(Map<String, PropertyDefinition> capabilityTypeProperties) {
- return capabilityTypeProperties.values().stream()
- .map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null))
- .collect(Collectors.toList());
+ return capabilityTypeProperties.values().stream().map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null))
+ .collect(Collectors.toList());
}
-
/**
* @param capabilityTypeRes
* @param capabilityTypeDefinition
* @return
*/
- private Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getPropertiesOfCapabilityTypeAndAcestors(CapabilityTypeDefinition capabilityTypeDefinition) {
+ private Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getPropertiesOfCapabilityTypeAndAcestors(
+ CapabilityTypeDefinition capabilityTypeDefinition) {
// Get the properties on the group type of this capability
Map<String, PropertyDefinition> capabilityTypeProperties = capabilityTypeDefinition.getProperties();
-
String derivedFrom = capabilityTypeDefinition.getDerivedFrom();
if (!Strings.isNullOrEmpty(derivedFrom)) {
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> parentPropsRes = capabilityTypeOperation.getAllCapabilityTypePropertiesFromAllDerivedFrom(derivedFrom);
- if(parentPropsRes.isRight()) {
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> parentPropsRes = capabilityTypeOperation
+ .getAllCapabilityTypePropertiesFromAllDerivedFrom(derivedFrom);
+ if (parentPropsRes.isRight()) {
JanusGraphOperationStatus status = parentPropsRes.right().value();
return Either.right(status);
}
@@ -281,14 +234,11 @@ public class CapabilityOperation extends AbstractOperation {
capabilityTypeProperties = parentPropsRes.left().value();
}
}
-
return Either.left(capabilityTypeProperties);
}
-
-
+
/**
- * Create all property values of the capability and their
- * relations to relevant properties of the capability type.
+ * Create all property values of the capability and their relations to relevant properties of the capability type.
*
* @param capabilityDefintion
* @param capabilityTypeData
@@ -296,104 +246,80 @@ public class CapabilityOperation extends AbstractOperation {
*/
private Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> createCapabilityProperties(CapabilityData capabilityData,
CapabilityTypeData capabilityTypeData) {
-
- CapabilityDefinition capabilityDefintion = (CapabilityDefinition)capabilityData.getCapabilityDataDefinition();
- CapabilityTypeDefinition capabilityTypeDefinition = (CapabilityTypeDefinition)capabilityTypeData.getCapabilityTypeDataDefinition();
-
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> typesPropsRes = getPropertiesOfCapabilityTypeAndAcestors(capabilityTypeDefinition);
+ CapabilityDefinition capabilityDefintion = (CapabilityDefinition) capabilityData.getCapabilityDataDefinition();
+ CapabilityTypeDefinition capabilityTypeDefinition = (CapabilityTypeDefinition) capabilityTypeData.getCapabilityTypeDataDefinition();
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> typesPropsRes = getPropertiesOfCapabilityTypeAndAcestors(
+ capabilityTypeDefinition);
if (typesPropsRes.isRight()) {
JanusGraphOperationStatus status = typesPropsRes.right().value();
return Either.right(status);
}
-
Map<String, PropertyDefinition> capabilityTypeProperties = typesPropsRes.left().value();
-
if (isEmpty(capabilityTypeProperties) && !isEmpty(capabilityDefintion.getProperties())) {
log.debug("#createCapabilityProperties - It's not valid if group capability has properties while corresponding capability type doesn't.");
return Either.right(JanusGraphOperationStatus.MATCH_NOT_FOUND);
}
-
Optional<JanusGraphOperationStatus> error = capabilityDefintion.getProperties().stream()
- .map(property -> createPropertyValue(property, capabilityData, capabilityTypeProperties.get(property.getName())))
- .filter(Either::isRight)
- .map(result -> result.right().value())
- .findFirst();
+ .map(property -> createPropertyValue(property, capabilityData, capabilityTypeProperties.get(property.getName()))).filter(Either::isRight)
+ .map(result -> result.right().value()).findFirst();
if (error.isPresent()) {
return Either.right(error.get());
}
-
return Either.left(capabilityDefintion.getProperties());
}
-
/**
* @param capabilityTypeProperties
* @param excludePropsWithUniqueIds
* @return
*/
- private List<ComponentInstanceProperty> filterCapabilityTypesProps(Map<String, PropertyDefinition> capabilityTypeProperties,
- Set<String> excludePropsWithNames) {
- return capabilityTypeProperties.values().stream()
- .filter(p -> !excludePropsWithNames.contains(p.getName()))
- .map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null))
- .collect(Collectors.toList());
+ private List<ComponentInstanceProperty> filterCapabilityTypesProps(Map<String, PropertyDefinition> capabilityTypeProperties,
+ Set<String> excludePropsWithNames) {
+ return capabilityTypeProperties.values().stream().filter(p -> !excludePropsWithNames.contains(p.getName()))
+ .map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
}
- private Either<PropertyValueData, JanusGraphOperationStatus> createPropertyValue(ComponentInstanceProperty capabilityProperty,
- CapabilityData capabilityData,
- PropertyDefinition capTypePropertyDefinition) {
+ private Either<PropertyValueData, JanusGraphOperationStatus> createPropertyValue(ComponentInstanceProperty capabilityProperty,
+ CapabilityData capabilityData,
+ PropertyDefinition capTypePropertyDefinition) {
if (capTypePropertyDefinition == null) {
return Either.right(JanusGraphOperationStatus.MATCH_NOT_FOUND);
}
-
- CapabilityDefinition capabilityDefintion = (CapabilityDefinition)capabilityData.getCapabilityDataDefinition();
-
- Either<Integer, StorageOperationStatus> indexRes =
- propertyOperation.increaseAndGetObjInstancePropertyCounter(capabilityDefintion.getUniqueId(), NodeTypeEnum.Capability);
- String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(capabilityDefintion.getUniqueId(), indexRes.left().value() );
+ CapabilityDefinition capabilityDefintion = (CapabilityDefinition) capabilityData.getCapabilityDataDefinition();
+ Either<Integer, StorageOperationStatus> indexRes = propertyOperation
+ .increaseAndGetObjInstancePropertyCounter(capabilityDefintion.getUniqueId(), NodeTypeEnum.Capability);
+ String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(capabilityDefintion.getUniqueId(), indexRes.left().value());
PropertyValueData propertyValueData = new PropertyValueData();
propertyValueData.setUniqueId(uniqueId);
propertyValueData.setValue(capabilityProperty.getValue());
- Either<PropertyValueData, JanusGraphOperationStatus> propResult = janusGraphGenericDao
- .createNode(propertyValueData, PropertyValueData.class);
+ Either<PropertyValueData, JanusGraphOperationStatus> propResult = janusGraphGenericDao.createNode(propertyValueData, PropertyValueData.class);
// It's not accepted if Capability Type doesn't have suitable property
- propResult = propResult.left()
- .bind(propValueData -> connectToProperty(propValueData, capTypePropertyDefinition))
- .left()
- .bind(graphRelation -> connectCapability(propertyValueData, capTypePropertyDefinition.getName(), capabilityData))
- .left()
- .map(graphRelation -> propertyValueData);
-
- propResult.left()
- .foreachDoEffect(propValueData -> capabilityProperty.setUniqueId(uniqueId));
-
+ propResult = propResult.left().bind(propValueData -> connectToProperty(propValueData, capTypePropertyDefinition)).left()
+ .bind(graphRelation -> connectCapability(propertyValueData, capTypePropertyDefinition.getName(), capabilityData)).left()
+ .map(graphRelation -> propertyValueData);
+ propResult.left().foreachDoEffect(propValueData -> capabilityProperty.setUniqueId(uniqueId));
return propResult;
}
-
- private Either<GraphRelation, JanusGraphOperationStatus> connectCapability(PropertyValueData propValueData, String name, CapabilityData capabilityData) {
+
+ private Either<GraphRelation, JanusGraphOperationStatus> connectCapability(PropertyValueData propValueData, String name,
+ CapabilityData capabilityData) {
Map<String, Object> properties = new HashMap<>();
properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), name);
-
return janusGraphGenericDao.createRelation(capabilityData, propValueData, GraphEdgeLabels.PROPERTY_VALUE, properties);
}
-
- private Either<GraphRelation, JanusGraphOperationStatus> connectToProperty(PropertyValueData propValueData, PropertyDefinition propertyDefinition) {
- Either<PropertyData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property),
- propertyDefinition.getUniqueId(), PropertyData.class);
+ private Either<GraphRelation, JanusGraphOperationStatus> connectToProperty(PropertyValueData propValueData,
+ PropertyDefinition propertyDefinition) {
+ Either<PropertyData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyDefinition.getUniqueId(), PropertyData.class);
Map<String, Object> properties = new HashMap<>();
properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), propertyDefinition.getName());
-
return dataTypesRes.left()
- .bind(propertyData -> janusGraphGenericDao
- .createRelation(propValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, properties));
+ .bind(propertyData -> janusGraphGenericDao.createRelation(propValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, properties));
}
-
private CapabilityData buildCapabilityData(CapabilityDefinition capabilityDefinition, String ctUniqueId) {
-
CapabilityData capabilityData = new CapabilityData(capabilityDefinition);
-
capabilityData.setUniqueId(ctUniqueId);
Long creationDate = capabilityData.getCreationTime();
if (creationDate == null) {
@@ -404,19 +330,11 @@ public class CapabilityOperation extends AbstractOperation {
return capabilityData;
}
-
public StorageOperationStatus deleteCapability(CapabilityDefinition capabilityDef) {
-
return janusGraphGenericDao
.deleteChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), capabilityDef.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE,
- NodeTypeEnum.PropertyValue, PropertyValueData.class)
- .left()
- .bind(props -> janusGraphGenericDao
- .deleteNode(new CapabilityData(capabilityDef), CapabilityData.class))
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
- .right()
- .on(capData -> StorageOperationStatus.OK);
+ NodeTypeEnum.PropertyValue, PropertyValueData.class).left()
+ .bind(props -> janusGraphGenericDao.deleteNode(new CapabilityData(capabilityDef), CapabilityData.class)).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus).right().on(capData -> StorageOperationStatus.OK);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java
index d03d989fb9..e845f4d989 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import fj.data.Either;
@@ -30,9 +29,9 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
@@ -48,6 +47,10 @@ import org.springframework.stereotype.Component;
@Component("capability-type-operation")
public class CapabilityTypeOperation extends AbstractOperation implements ICapabilityTypeOperation {
+
+ private static final Logger log = Logger.getLogger(CapabilityTypeOperation.class.getName());
+ private static final String DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS = "Data type {} cannot be found in graph." + " status is {}";
+ private static final String FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE = "Failed to fetch properties of data type {}";
@Autowired
private PropertyOperation propertyOperation;
@Autowired
@@ -57,12 +60,6 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
super();
}
- private static final Logger log = Logger.getLogger(CapabilityTypeOperation.class.getName());
- private static final String DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS = "Data type {} cannot be found in graph."
- + " status is {}";
- private static final String FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE = "Failed to fetch properties of data type {}";
-
-
/**
* FOR TEST ONLY
*
@@ -73,32 +70,23 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
@Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction) {
-
+ public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition,
+ boolean inTransaction) {
Either<CapabilityTypeDefinition, StorageOperationStatus> result = null;
-
try {
Either<CapabilityTypeDefinition, StorageOperationStatus> validationRes = validateUpdateProperties(capabilityTypeDefinition);
if (validationRes.isRight()) {
- log.error("#addCapabilityType - One or all properties of capability type {} not valid. status is {}", capabilityTypeDefinition, validationRes.right().value());
+ log.error("#addCapabilityType - One or all properties of capability type {} not valid. status is {}", capabilityTypeDefinition,
+ validationRes.right().value());
return result;
}
-
Either<CapabilityTypeData, StorageOperationStatus> eitherStatus = addCapabilityTypeToGraph(capabilityTypeDefinition);
-
- result = eitherStatus.left()
- .map(CapabilityTypeData::getUniqueId)
- .left()
- .bind(uniqueId -> getCapabilityType(uniqueId, inTransaction));
-
- if(result.isLeft()) {
+ result = eitherStatus.left().map(CapabilityTypeData::getUniqueId).left().bind(uniqueId -> getCapabilityType(uniqueId, inTransaction));
+ if (result.isLeft()) {
log.debug("#addCapabilityType - The returned CapabilityTypeDefinition is {}", result.left().value());
}
-
return result;
- }
-
- finally {
+ } finally {
if (!inTransaction) {
if (result == null || result.isRight()) {
log.error("#addCapabilityType - Going to execute rollback on graph.");
@@ -109,31 +97,30 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
}
}
-
}
-
- public Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType) {
+
+ public Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(
+ String firstParentType) {
return propertyOperation.getAllTypePropertiesFromAllDerivedFrom(firstParentType, NodeTypeEnum.CapabilityType, CapabilityTypeData.class);
}
public Either<CapabilityTypeDefinition, StorageOperationStatus> validateUpdateProperties(CapabilityTypeDefinition capabilityTypeDefinition) {
JanusGraphOperationStatus error = null;
if (MapUtils.isNotEmpty(capabilityTypeDefinition.getProperties()) && capabilityTypeDefinition.getDerivedFrom() != null) {
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> allPropertiesRes =
- getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeDefinition.getDerivedFrom());
- if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals(
- JanusGraphOperationStatus.NOT_FOUND)) {
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> allPropertiesRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(
+ capabilityTypeDefinition.getDerivedFrom());
+ if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
error = allPropertiesRes.right().value();
log.debug("Couldn't fetch derived from property nodes for capability type {}, error: {}", capabilityTypeDefinition.getType(), error);
}
if (error == null && !allPropertiesRes.left().value().isEmpty()) {
Map<String, PropertyDefinition> derivedFromProperties = allPropertiesRes.left().value();
- capabilityTypeDefinition.getProperties().entrySet().stream().filter(e -> derivedFromProperties.containsKey(e.getKey()) && e.getValue().getType() == null)
- .forEach(e -> e.getValue().setType(derivedFromProperties.get(e.getKey()).getType()));
-
+ capabilityTypeDefinition.getProperties().entrySet().stream()
+ .filter(e -> derivedFromProperties.containsKey(e.getKey()) && e.getValue().getType() == null)
+ .forEach(e -> e.getValue().setType(derivedFromProperties.get(e.getKey()).getType()));
List<PropertyDefinition> properties = capabilityTypeDefinition.getProperties().values().stream().collect(Collectors.toList());
- Either<List<PropertyDefinition>, JanusGraphOperationStatus> validatePropertiesRes = propertyOperation.validatePropertiesUniqueness(allPropertiesRes.left().value(),
- properties);
+ Either<List<PropertyDefinition>, JanusGraphOperationStatus> validatePropertiesRes = propertyOperation
+ .validatePropertiesUniqueness(allPropertiesRes.left().value(), properties);
if (validatePropertiesRes.isRight()) {
error = validatePropertiesRes.right().value();
}
@@ -144,58 +131,45 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
-
/**
- *
* Add capability type to graph.
- *
+ * <p>
* 1. Add capability type node
- *
+ * <p>
* 2. Add edge between the former node to its parent(if exists)
- *
+ * <p>
* 3. Add property node and associate it to the node created at #1. (per property & if exists)
*
* @param capabilityTypeDefinition
* @return
*/
private Either<CapabilityTypeData, StorageOperationStatus> addCapabilityTypeToGraph(CapabilityTypeDefinition capabilityTypeDefinition) {
-
log.debug("Got capability type {}", capabilityTypeDefinition);
-
String ctUniqueId = UniqueIdBuilder.buildCapabilityTypeUid(capabilityTypeDefinition.getType());
CapabilityTypeData capabilityTypeData = buildCapabilityTypeData(capabilityTypeDefinition, ctUniqueId);
-
log.debug("Before adding capability type to graph. capabilityTypeData = {}", capabilityTypeData);
Either<CapabilityTypeData, JanusGraphOperationStatus> createCTResult = janusGraphGenericDao
.createNode(capabilityTypeData, CapabilityTypeData.class);
log.debug("After adding capability type to graph. status is = {}", createCTResult);
-
if (createCTResult.isRight()) {
JanusGraphOperationStatus operationStatus = createCTResult.right().value();
log.error("Failed to capability type {} to graph. status is {}", capabilityTypeDefinition.getType(), operationStatus);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus));
}
-
CapabilityTypeData resultCTD = createCTResult.left().value();
Map<String, PropertyDefinition> propertiesMap = capabilityTypeDefinition.getProperties();
- Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.CapabilityType, propertiesMap);
+ Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToCapablityType = propertyOperation
+ .addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.CapabilityType, propertiesMap);
if (addPropertiesToCapablityType.isRight()) {
log.error("Failed add properties {} to capability {}", propertiesMap, capabilityTypeDefinition.getType());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertiesToCapablityType.right().value()));
}
-
- return addDerivedFromRelation(capabilityTypeDefinition, ctUniqueId)
- .left()
- .map(updatedDerivedFrom -> createCTResult.left().value());
-
-
+ return addDerivedFromRelation(capabilityTypeDefinition, ctUniqueId).left().map(updatedDerivedFrom -> createCTResult.left().value());
}
private CapabilityTypeData buildCapabilityTypeData(CapabilityTypeDefinition capabilityTypeDefinition, String ctUniqueId) {
-
CapabilityTypeData capabilityTypeData = new CapabilityTypeData(capabilityTypeDefinition);
-
capabilityTypeData.getCapabilityTypeDataDefinition().setUniqueId(ctUniqueId);
Long creationDate = capabilityTypeData.getCapabilityTypeDataDefinition().getCreationTime();
if (creationDate == null) {
@@ -208,12 +182,9 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
@Override
public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId, boolean inTransaction) {
-
Either<CapabilityTypeDefinition, StorageOperationStatus> result = null;
try {
-
Either<CapabilityTypeDefinition, JanusGraphOperationStatus> ctResult = this.getCapabilityTypeByUid(uniqueId);
-
if (ctResult.isRight()) {
JanusGraphOperationStatus status = ctResult.right().value();
if (status != JanusGraphOperationStatus.NOT_FOUND) {
@@ -222,9 +193,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value()));
return result;
}
-
result = Either.left(ctResult.left().value());
-
return result;
} finally {
if (!inTransaction) {
@@ -234,7 +203,6 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
}
-
public Either<CapabilityTypeDefinition, JanusGraphOperationStatus> getCapabilityTypeByType(String capabilityType) {
// Optimization: In case of Capability Type its unique ID is the same as type
return getCapabilityTypeByUid(capabilityType);
@@ -247,32 +215,25 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
* @return
*/
public Either<CapabilityTypeDefinition, JanusGraphOperationStatus> getCapabilityTypeByUid(String uniqueId) {
-
Either<CapabilityTypeDefinition, JanusGraphOperationStatus> result = null;
-
Either<CapabilityTypeData, JanusGraphOperationStatus> capabilityTypesRes = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, CapabilityTypeData.class);
-
if (capabilityTypesRes.isRight()) {
JanusGraphOperationStatus status = capabilityTypesRes.right().value();
log.debug("Capability type {} cannot be found in graph. status is {}", uniqueId, status);
return Either.right(status);
}
-
CapabilityTypeData ctData = capabilityTypesRes.left().value();
CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(ctData.getCapabilityTypeDataDefinition());
-
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesStatus =
- OperationUtils.fillProperties(uniqueId, propertyOperation, NodeTypeEnum.CapabilityType);
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesStatus = OperationUtils
+ .fillProperties(uniqueId, propertyOperation, NodeTypeEnum.CapabilityType);
if (propertiesStatus.isRight() && propertiesStatus.right().value() != JanusGraphOperationStatus.OK) {
log.error("Failed to fetch properties of capability type {}", uniqueId);
return Either.right(propertiesStatus.right().value());
}
-
if (propertiesStatus.isLeft()) {
capabilityTypeDefinition.setProperties(propertiesStatus.left().value());
}
-
Either<ImmutablePair<CapabilityTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, GraphEdgeLabels.DERIVED_FROM,
NodeTypeEnum.CapabilityType, CapabilityTypeData.class);
@@ -280,8 +241,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
if (parentNode.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
- log.error("Failed to find the parent capability of capability type {}. status is {}", uniqueId,
- janusGraphOperationStatus);
+ log.error("Failed to find the parent capability of capability type {}. status is {}", uniqueId, janusGraphOperationStatus);
result = Either.right(janusGraphOperationStatus);
return result;
}
@@ -292,67 +252,64 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
capabilityTypeDefinition.setDerivedFrom(parentCT.getCapabilityTypeDataDefinition().getType());
}
result = Either.left(capabilityTypeDefinition);
-
return result;
}
public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType, String parentCandidateType) {
- return derivedFromOperation.isTypeDerivedFrom(childCandidateType, parentCandidateType, null, NodeTypeEnum.CapabilityType, CapabilityTypeData.class, t -> t.getCapabilityTypeDataDefinition().getType());
+ return derivedFromOperation
+ .isTypeDerivedFrom(childCandidateType, parentCandidateType, null, NodeTypeEnum.CapabilityType, CapabilityTypeData.class,
+ t -> t.getCapabilityTypeDataDefinition().getType());
}
-
-
+
@Override
- public Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityType(CapabilityTypeDefinition capabilityTypeDefNew,
+ public Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityType(CapabilityTypeDefinition capabilityTypeDefNew,
CapabilityTypeDefinition capabilityTypeDefOld) {
log.debug("updating capability type {}", capabilityTypeDefNew.getType());
updateCapabilityTypeData(capabilityTypeDefNew, capabilityTypeDefOld);
return updateCapabilityTypeOnGraph(capabilityTypeDefNew, capabilityTypeDefOld);
}
-
-
- private Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityTypeOnGraph(CapabilityTypeDefinition capabilityTypeDefinitionNew, CapabilityTypeDefinition capabilityTypeDefinitionOld) {
- return janusGraphGenericDao
- .updateNode(new CapabilityTypeData(capabilityTypeDefinitionNew), CapabilityTypeData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
- .left()
- .bind(updatedNode -> updateProperties(capabilityTypeDefinitionNew.getUniqueId(), capabilityTypeDefinitionNew.getProperties()))
- .left()
- .bind(updatedProperties -> updateDerivedFrom(capabilityTypeDefinitionNew, capabilityTypeDefinitionOld.getDerivedFrom()))
- .right()
- .bind(result -> TypeOperations.mapOkStatus(result, null))
- .left()
- .map(updatedDerivedFrom -> capabilityTypeDefinitionNew);
+
+ private Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityTypeOnGraph(CapabilityTypeDefinition capabilityTypeDefinitionNew,
+ CapabilityTypeDefinition capabilityTypeDefinitionOld) {
+ return janusGraphGenericDao.updateNode(new CapabilityTypeData(capabilityTypeDefinitionNew), CapabilityTypeData.class).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus).left()
+ .bind(updatedNode -> updateProperties(capabilityTypeDefinitionNew.getUniqueId(), capabilityTypeDefinitionNew.getProperties())).left()
+ .bind(updatedProperties -> updateDerivedFrom(capabilityTypeDefinitionNew, capabilityTypeDefinitionOld.getDerivedFrom())).right()
+ .bind(result -> TypeOperations.mapOkStatus(result, null)).left().map(updatedDerivedFrom -> capabilityTypeDefinitionNew);
}
- private Either<Map<String, PropertyData>, StorageOperationStatus> updateProperties(String capabilityTypeId, Map<String, PropertyDefinition> properties) {
+ private Either<Map<String, PropertyData>, StorageOperationStatus> updateProperties(String capabilityTypeId,
+ Map<String, PropertyDefinition> properties) {
log.debug("#updateCapabilityTypeProperties - updating properties for capability type with id {}", capabilityTypeId);
- return propertyOperation.mergePropertiesAssociatedToNode(NodeTypeEnum.CapabilityType, capabilityTypeId, properties)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ return propertyOperation.mergePropertiesAssociatedToNode(NodeTypeEnum.CapabilityType, capabilityTypeId, properties).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
- private Either<GraphRelation, StorageOperationStatus> updateDerivedFrom(CapabilityTypeDefinition updatedCapabilityType, String currDerivedFromCapabilityType) {
- if( StringUtils.equals(updatedCapabilityType.getDerivedFrom(), currDerivedFromCapabilityType)) {
+ private Either<GraphRelation, StorageOperationStatus> updateDerivedFrom(CapabilityTypeDefinition updatedCapabilityType,
+ String currDerivedFromCapabilityType) {
+ if (StringUtils.equals(updatedCapabilityType.getDerivedFrom(), currDerivedFromCapabilityType)) {
return Either.right(StorageOperationStatus.OK);
}
-
- StorageOperationStatus status = isLegalToReplaceParent(currDerivedFromCapabilityType, updatedCapabilityType.getDerivedFrom(), updatedCapabilityType.getType());
- if ( status != StorageOperationStatus.OK) {
+ StorageOperationStatus status = isLegalToReplaceParent(currDerivedFromCapabilityType, updatedCapabilityType.getDerivedFrom(),
+ updatedCapabilityType.getType());
+ if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
-
String capabilityTypeId = updatedCapabilityType.getUniqueId();
- log.debug("#updateCapabilityTypeDerivedFrom - updating capability type derived from relation for capability type with id {}. old derived type {}. new derived type {}", capabilityTypeId, currDerivedFromCapabilityType, updatedCapabilityType.getDerivedFrom());
+ log.debug(
+ "#updateCapabilityTypeDerivedFrom - updating capability type derived from relation for capability type with id {}. old derived type {}. new derived type {}",
+ capabilityTypeId, currDerivedFromCapabilityType, updatedCapabilityType.getDerivedFrom());
StorageOperationStatus deleteDerivedRelationStatus = deleteDerivedFromCapabilityType(capabilityTypeId, currDerivedFromCapabilityType);
if (deleteDerivedRelationStatus != StorageOperationStatus.OK) {
return Either.right(deleteDerivedRelationStatus);
}
return addDerivedFromRelation(updatedCapabilityType, capabilityTypeId);
}
-
+
private StorageOperationStatus isLegalToReplaceParent(String oldTypeParent, String newTypeParent, String childType) {
- return derivedFromOperation.isUpdateParentAllowed(oldTypeParent, newTypeParent, childType, NodeTypeEnum.CapabilityType, CapabilityTypeData.class, t -> t.getCapabilityTypeDataDefinition().getType());
+ return derivedFromOperation
+ .isUpdateParentAllowed(oldTypeParent, newTypeParent, childType, NodeTypeEnum.CapabilityType, CapabilityTypeData.class,
+ t -> t.getCapabilityTypeDataDefinition().getType());
}
private Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(CapabilityTypeDefinition capabilityTypeDef, String ptUniqueId) {
@@ -360,28 +317,27 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
if (derivedFrom == null) {
return Either.left(null);
}
- log.debug("#addDerivedFromRelationBefore - adding derived from relation between capability type {} to its parent {}", capabilityTypeDef.getType(), derivedFrom);
- return this.getCapabilityType(derivedFrom, true)
- .left()
- .bind(derivedFromCapabilityType -> derivedFromOperation.addDerivedFromRelation(ptUniqueId, derivedFromCapabilityType.getUniqueId(), NodeTypeEnum.CapabilityType));
+ log.debug("#addDerivedFromRelationBefore - adding derived from relation between capability type {} to its parent {}",
+ capabilityTypeDef.getType(), derivedFrom);
+ return this.getCapabilityType(derivedFrom, true).left().bind(derivedFromCapabilityType -> derivedFromOperation
+ .addDerivedFromRelation(ptUniqueId, derivedFromCapabilityType.getUniqueId(), NodeTypeEnum.CapabilityType));
}
private StorageOperationStatus deleteDerivedFromCapabilityType(String capabilityTypeId, String derivedFromType) {
if (derivedFromType == null) {
return StorageOperationStatus.OK;
}
- log.debug("#deleteDerivedFromCapabilityType - deleting derivedFrom relation for capability type with id {} and its derived type {}", capabilityTypeId, derivedFromType);
- return getCapabilityType(derivedFromType, true)
- .either(derivedFromNode -> derivedFromOperation.removeDerivedFromRelation(capabilityTypeId, derivedFromNode.getUniqueId(), NodeTypeEnum.CapabilityType),
- err -> err);
- }
-
+ log.debug("#deleteDerivedFromCapabilityType - deleting derivedFrom relation for capability type with id {} and its derived type {}",
+ capabilityTypeId, derivedFromType);
+ return getCapabilityType(derivedFromType, true).either(derivedFromNode -> derivedFromOperation
+ .removeDerivedFromRelation(capabilityTypeId, derivedFromNode.getUniqueId(), NodeTypeEnum.CapabilityType), err -> err);
+ }
+
private void updateCapabilityTypeData(CapabilityTypeDefinition updatedTypeDefinition, CapabilityTypeDefinition currTypeDefinition) {
updatedTypeDefinition.setUniqueId(currTypeDefinition.getUniqueId());
updatedTypeDefinition.setCreationTime(currTypeDefinition.getCreationTime());
}
-
/**
* FOR TEST ONLY
*
@@ -393,7 +349,6 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
@Override
public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition) {
-
return addCapabilityType(capabilityTypeDefinition, true);
}
@@ -401,14 +356,12 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId) {
return getCapabilityType(uniqueId, true);
}
- public Either<Map<String, CapabilityTypeDefinition>, JanusGraphOperationStatus> getAllCapabilityTypes() {
+ public Either<Map<String, CapabilityTypeDefinition>, JanusGraphOperationStatus> getAllCapabilityTypes() {
Map<String, CapabilityTypeDefinition> capabilityTypes = new HashMap<>();
Either<Map<String, CapabilityTypeDefinition>, JanusGraphOperationStatus> result = Either.left(capabilityTypes);
-
- Either<List<CapabilityTypeData>, JanusGraphOperationStatus> getAllCapabilityTypes =
- janusGraphGenericDao
- .getByCriteria(NodeTypeEnum.CapabilityType, null, CapabilityTypeData.class);
+ Either<List<CapabilityTypeData>, JanusGraphOperationStatus> getAllCapabilityTypes = janusGraphGenericDao
+ .getByCriteria(NodeTypeEnum.CapabilityType, null, CapabilityTypeData.class);
if (getAllCapabilityTypes.isRight()) {
JanusGraphOperationStatus status = getAllCapabilityTypes.right().value();
if (status != JanusGraphOperationStatus.NOT_FOUND) {
@@ -417,19 +370,15 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
return result;
}
}
-
List<CapabilityTypeData> list = getAllCapabilityTypes.left().value();
if (list != null) {
-
log.trace("Number of data types to load is {}", list.size());
//Set properties
for (CapabilityTypeData capabilityTypeData : list) {
-
- log.trace("Going to fetch data type {}. uid is {}",
- capabilityTypeData.getCapabilityTypeDataDefinition().getType(),
- capabilityTypeData.getUniqueId());
- Either<CapabilityTypeDefinition, JanusGraphOperationStatus> capabilityTypesByUid =
- getAndAddPropertiesANdDerivedFrom(capabilityTypeData.getUniqueId(), capabilityTypes);
+ log.trace("Going to fetch data type {}. uid is {}", capabilityTypeData.getCapabilityTypeDataDefinition().getType(),
+ capabilityTypeData.getUniqueId());
+ Either<CapabilityTypeDefinition, JanusGraphOperationStatus> capabilityTypesByUid = getAndAddPropertiesANdDerivedFrom(
+ capabilityTypeData.getUniqueId(), capabilityTypes);
if (capabilityTypesByUid.isRight()) {
JanusGraphOperationStatus status = capabilityTypesByUid.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -439,18 +388,13 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
}
}
-
return result;
}
private void fillDerivedFrom(String uniqueId, CapabilityTypeDefinition capabilityType) {
log.debug("#fillDerivedFrom - fetching capability type {} derived node", capabilityType.getType());
- derivedFromOperation.getDerivedFromChild(uniqueId, NodeTypeEnum.CapabilityType, CapabilityTypeData.class)
- .right()
- .bind(this::handleDerivedFromNotExist)
- .left()
- .map(derivedFrom -> setDerivedFrom(capabilityType, derivedFrom));
-
+ derivedFromOperation.getDerivedFromChild(uniqueId, NodeTypeEnum.CapabilityType, CapabilityTypeData.class).right()
+ .bind(this::handleDerivedFromNotExist).left().map(derivedFrom -> setDerivedFrom(capabilityType, derivedFrom));
}
private Either<CapabilityTypeData, StorageOperationStatus> handleDerivedFromNotExist(StorageOperationStatus err) {
@@ -467,43 +411,31 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
return derivedFrom;
}
- private Either<CapabilityTypeDefinition, JanusGraphOperationStatus> getAndAddPropertiesANdDerivedFrom(
- String uniqueId, Map<String, CapabilityTypeDefinition> capabilityTypeDefinitionMap) {
+ private Either<CapabilityTypeDefinition, JanusGraphOperationStatus> getAndAddPropertiesANdDerivedFrom(String uniqueId,
+ Map<String, CapabilityTypeDefinition> capabilityTypeDefinitionMap) {
if (capabilityTypeDefinitionMap.containsKey(uniqueId)) {
return Either.left(capabilityTypeDefinitionMap.get(uniqueId));
}
-
- Either<CapabilityTypeData, JanusGraphOperationStatus> capabilityTypesRes =
- janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId,
- CapabilityTypeData.class);
-
+ Either<CapabilityTypeData, JanusGraphOperationStatus> capabilityTypesRes = janusGraphGenericDao
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, CapabilityTypeData.class);
if (capabilityTypesRes.isRight()) {
JanusGraphOperationStatus status = capabilityTypesRes.right().value();
log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
return Either.right(status);
}
-
CapabilityTypeData ctData = capabilityTypesRes.left().value();
- CapabilityTypeDefinition capabilityTypeDefinition =
- new CapabilityTypeDefinition(ctData.getCapabilityTypeDataDefinition());
-
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesStatus =
- OperationUtils.fillProperties(uniqueId, propertyOperation, NodeTypeEnum.CapabilityType);
-
+ CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(ctData.getCapabilityTypeDataDefinition());
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesStatus = OperationUtils
+ .fillProperties(uniqueId, propertyOperation, NodeTypeEnum.CapabilityType);
if (propertiesStatus.isRight() && propertiesStatus.right().value() != JanusGraphOperationStatus.OK) {
log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
return Either.right(propertiesStatus.right().value());
}
-
if (propertiesStatus.isLeft()) {
capabilityTypeDefinition.setProperties(propertiesStatus.left().value());
}
-
fillDerivedFrom(uniqueId, capabilityTypeDefinition);
-
capabilityTypeDefinitionMap.put(capabilityTypeDefinition.getType(), capabilityTypeDefinition);
-
return Either.left(capabilityTypeDefinition);
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java
index f8a43ca3c7..a9dc6bd672 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import static java.util.Collections.emptyList;
@@ -31,8 +30,8 @@ import java.util.function.Function;
import java.util.stream.Collectors;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.springframework.stereotype.Component;
@@ -52,15 +51,11 @@ public class CommonTypeOperations {
}
public <T extends GraphNode> void addType(T typeData, Class<T> clazz) {
- janusGraphGenericDao.createNode(typeData, clazz)
- .left()
- .on(operationUtils::onJanusGraphOperationFailure);
+ janusGraphGenericDao.createNode(typeData, clazz).left().on(operationUtils::onJanusGraphOperationFailure);
}
public <T extends GraphNode> Optional<T> getType(String uniqueId, Class<T> clazz, NodeTypeEnum nodeType) {
- T type = janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, clazz)
- .left()
- .on(err -> null);
+ T type = janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, clazz).left().on(err -> null);
return Optional.ofNullable(type);
}
@@ -68,23 +63,16 @@ public class CommonTypeOperations {
Map<String, Object> mapCriteria = new HashMap<>();
mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type);
mapCriteria.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- return janusGraphGenericDao.getByCriteria(nodeType, mapCriteria, clazz)
- .left()
- .on(err -> emptyList())
- .stream()
- .findFirst();
+ return janusGraphGenericDao.getByCriteria(nodeType, mapCriteria, clazz).left().on(err -> emptyList()).stream().findFirst();
}
public void addProperties(String uniqueId, NodeTypeEnum nodeType, List<PropertyDefinition> properties) {
- propertyOperation.addPropertiesToElementType(uniqueId, nodeType, properties)
- .left()
- .on(operationUtils::onJanusGraphOperationFailure);
+ propertyOperation.addPropertiesToElementType(uniqueId, nodeType, properties).left().on(operationUtils::onJanusGraphOperationFailure);
}
public void fillProperties(String uniqueId, NodeTypeEnum nodeType, Consumer<List<PropertyDefinition>> propertySetter) {
- JanusGraphOperationStatus
- status = propertyOperation.fillPropertiesList(uniqueId, nodeType, propertySetter);
- if (status!= JanusGraphOperationStatus.OK) {
+ JanusGraphOperationStatus status = propertyOperation.fillPropertiesList(uniqueId, nodeType, propertySetter);
+ if (status != JanusGraphOperationStatus.OK) {
operationUtils.onJanusGraphOperationFailure(status);
}
}
@@ -92,14 +80,11 @@ public class CommonTypeOperations {
/**
* Handle update of type without dervidedFrom attribute
*/
- public <T extends GraphNode> void updateType(T typeData, List<PropertyDefinition> properties, Class<T> clazz, NodeTypeEnum nodeType) {
- janusGraphGenericDao.updateNode(typeData, clazz)
- .left()
- .on(operationUtils::onJanusGraphOperationFailure);
+ public <T extends GraphNode> void updateType(T typeData, List<PropertyDefinition> properties, Class<T> clazz, NodeTypeEnum nodeType) {
+ janusGraphGenericDao.updateNode(typeData, clazz).left().on(operationUtils::onJanusGraphOperationFailure);
Map<String, PropertyDefinition> newProperties = properties.stream()
- .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
- propertyOperation.mergePropertiesAssociatedToNode(nodeType, typeData.getUniqueId(), newProperties)
- .left()
- .on(operationUtils::onJanusGraphOperationFailure);
+ .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
+ propertyOperation.mergePropertiesAssociatedToNode(nodeType, typeData.getUniqueId(), newProperties).left()
+ .on(operationUtils::onJanusGraphOperationFailure);
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java
index f4ad0b2c09..1097e5d204 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
import fj.F;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphVertex;
import fj.data.Either;
import java.util.HashMap;
import java.util.Map;
@@ -31,16 +28,18 @@ import java.util.function.Supplier;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphVertex;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -65,21 +64,18 @@ import org.springframework.beans.factory.annotation.Autowired;
@org.springframework.stereotype.Component("component-instance-operation")
public class ComponentInstanceOperation extends AbstractOperation {
- public ComponentInstanceOperation() {
- super();
- }
-
private static final Logger log = Logger.getLogger(ComponentInstanceOperation.class.getName());
-
@Autowired
PropertyOperation propertyOperation;
-
@Autowired
private IInputsOperation inputOperation;
-
@Autowired
private ApplicationDataTypeCache dataTypeCache;
+ public ComponentInstanceOperation() {
+ super();
+ }
+
/**
* FOR TEST ONLY
*
@@ -89,11 +85,11 @@ public class ComponentInstanceOperation extends AbstractOperation {
this.janusGraphGenericDao = janusGraphGenericDao;
}
- public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction) {
-
+ public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId,
+ GraphPropertiesDictionary counterType,
+ boolean inTransaction) {
Either<Integer, StorageOperationStatus> result = null;
try {
-
Either<JanusGraph, JanusGraphOperationStatus> graphResult = janusGraphGenericDao.getGraph();
if (graphResult.isRight()) {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graphResult.right().value()));
@@ -106,7 +102,6 @@ public class ComponentInstanceOperation extends AbstractOperation {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexService.right().value()));
}
Vertex vertex = vertexService.left().value();
-
VertexProperty<Object> vertexProperty = vertex.property(counterType.getProperty());
Integer counter = 0;
if (vertexProperty.isPresent()) {
@@ -114,13 +109,10 @@ public class ComponentInstanceOperation extends AbstractOperation {
counter = (Integer) vertexProperty.value();
}
}
-
counter++;
vertex.property(counterType.getProperty(), counter);
-
result = Either.left(counter);
return result;
-
} finally {
if (!inTransaction) {
if (result == null || result.isRight()) {
@@ -132,63 +124,61 @@ public class ComponentInstanceOperation extends AbstractOperation {
}
}
}
-
}
- private void connectAttValueDataToComponentInstanceData(Wrapper<JanusGraphOperationStatus> errorWrapper, ComponentInstanceData compIns, AttributeValueData attValueData) {
-
+ private void connectAttValueDataToComponentInstanceData(Wrapper<JanusGraphOperationStatus> errorWrapper, ComponentInstanceData compIns,
+ AttributeValueData attValueData) {
Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
.createRelation(compIns, attValueData, GraphEdgeLabels.ATTRIBUTE_VALUE, null);
-
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createRelResult.right().value();
errorWrapper.setInnerElement(operationStatus);
BeEcompErrorManager.getInstance().logInternalFlowError("connectAttValueDataToComponentInstanceData",
- "Failed to associate resource instance " + compIns.getUniqueId() + " attribute value " + attValueData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR);
+ "Failed to associate resource instance " + compIns.getUniqueId() + " attribute value " + attValueData.getUniqueId()
+ + " in graph. status is " + operationStatus, ErrorSeverity.ERROR);
}
}
- private void connectAttValueDataToAttData(Wrapper<JanusGraphOperationStatus> errorWrapper, AttributeData attData, AttributeValueData attValueData) {
-
+ private void connectAttValueDataToAttData(Wrapper<JanusGraphOperationStatus> errorWrapper, AttributeData attData,
+ AttributeValueData attValueData) {
Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
.createRelation(attValueData, attData, GraphEdgeLabels.ATTRIBUTE_IMPL, null);
-
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createRelResult.right().value();
BeEcompErrorManager.getInstance().logInternalFlowError("connectAttValueDataToAttData",
- "Failed to associate attribute value " + attValueData.getUniqueId() + " to attribute " + attData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR);
-
+ "Failed to associate attribute value " + attValueData.getUniqueId() + " to attribute " + attData.getUniqueId()
+ + " in graph. status is " + operationStatus, ErrorSeverity.ERROR);
errorWrapper.setInnerElement(operationStatus);
}
}
- private void createAttributeValueDataNode(ComponentInstanceProperty attributeInstanceProperty, Integer index, Wrapper<JanusGraphOperationStatus> errorWrapper, ComponentInstanceData resourceInstanceData,
+ private void createAttributeValueDataNode(ComponentInstanceProperty attributeInstanceProperty, Integer index,
+ Wrapper<JanusGraphOperationStatus> errorWrapper, ComponentInstanceData resourceInstanceData,
Wrapper<AttributeValueData> attValueDataWrapper) {
String valueUniqueUid = attributeInstanceProperty.getValueUniqueUid();
if (valueUniqueUid == null) {
-
String attValueDatauniqueId = UniqueIdBuilder.buildResourceInstanceAttributeValueUid(resourceInstanceData.getUniqueId(), index);
- AttributeValueData attributeValueData = buildAttributeValueDataFromComponentInstanceAttribute(attributeInstanceProperty, attValueDatauniqueId);
-
+ AttributeValueData attributeValueData = buildAttributeValueDataFromComponentInstanceAttribute(attributeInstanceProperty,
+ attValueDatauniqueId);
log.debug("Before adding attribute value to graph {}", attributeValueData);
Either<AttributeValueData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
.createNode(attributeValueData, AttributeValueData.class);
log.debug("After adding attribute value to graph {}", attributeValueData);
-
if (createNodeResult.isRight()) {
JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
errorWrapper.setInnerElement(operationStatus);
} else {
attValueDataWrapper.setInnerElement(createNodeResult.left().value());
}
-
} else {
- BeEcompErrorManager.getInstance().logInternalFlowError("CreateAttributeValueDataNode", "attribute value already exists.", ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("CreateAttributeValueDataNode", "attribute value already exists.", ErrorSeverity.ERROR);
errorWrapper.setInnerElement(JanusGraphOperationStatus.ALREADY_EXIST);
}
}
- private AttributeValueData buildAttributeValueDataFromComponentInstanceAttribute(ComponentInstanceProperty resourceInstanceAttribute, String uniqueId) {
+ private AttributeValueData buildAttributeValueDataFromComponentInstanceAttribute(ComponentInstanceProperty resourceInstanceAttribute,
+ String uniqueId) {
AttributeValueData attributeValueData = new AttributeValueData();
attributeValueData.setUniqueId(uniqueId);
attributeValueData.setHidden(resourceInstanceAttribute.isHidden());
@@ -200,55 +190,6 @@ public class ComponentInstanceOperation extends AbstractOperation {
return attributeValueData;
}
- private static final class UpdateDataContainer<SomeData, SomeValueData> {
- final Wrapper<SomeValueData> valueDataWrapper;
- final Wrapper<SomeData> dataWrapper;
- final GraphEdgeLabels graphEdge;
- final Supplier<Class<SomeData>> someDataClassGen;
- final Supplier<Class<SomeValueData>> someValueDataClassGen;
- final NodeTypeEnum nodeType;
- final NodeTypeEnum nodeTypeValue;
-
- private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier<Class<SomeData>> someDataClassGen, Supplier<Class<SomeValueData>> someValueDataClassGen, NodeTypeEnum nodeType, NodeTypeEnum nodeTypeValue) {
- super();
- this.valueDataWrapper = new Wrapper<>();
- this.dataWrapper = new Wrapper<>();
- this.graphEdge = graphEdge;
- this.someDataClassGen = someDataClassGen;
- this.someValueDataClassGen = someValueDataClassGen;
- this.nodeType = nodeType;
- this.nodeTypeValue = nodeTypeValue;
- }
-
- public Wrapper<SomeValueData> getValueDataWrapper() {
- return valueDataWrapper;
- }
-
- public Wrapper<SomeData> getDataWrapper() {
- return dataWrapper;
- }
-
- public GraphEdgeLabels getGraphEdge() {
- return graphEdge;
- }
-
- public Supplier<Class<SomeData>> getSomeDataClassGen() {
- return someDataClassGen;
- }
-
- public Supplier<Class<SomeValueData>> getSomeValueDataClassGen() {
- return someValueDataClassGen;
- }
-
- public NodeTypeEnum getNodeType() {
- return nodeType;
- }
-
- public NodeTypeEnum getNodeTypeValue() {
- return nodeTypeValue;
- }
- }
-
/**
* update value of attribute on resource instance
*
@@ -256,36 +197,34 @@ public class ComponentInstanceOperation extends AbstractOperation {
* @param resourceInstanceId
* @return
*/
- private Either<AttributeValueData, JanusGraphOperationStatus> updateAttributeOfResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId) {
+ private Either<AttributeValueData, JanusGraphOperationStatus> updateAttributeOfResourceInstance(
+ ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId) {
Wrapper<JanusGraphOperationStatus> errorWrapper = new Wrapper<>();
- UpdateDataContainer<AttributeData, AttributeValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.ATTRIBUTE_IMPL, (() -> AttributeData.class), (() -> AttributeValueData.class), NodeTypeEnum.Attribute,
- NodeTypeEnum.AttributeValue);
+ UpdateDataContainer<AttributeData, AttributeValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.ATTRIBUTE_IMPL,
+ (() -> AttributeData.class), (() -> AttributeValueData.class), NodeTypeEnum.Attribute, NodeTypeEnum.AttributeValue);
preUpdateElementOfResourceInstanceValidations(updateDataContainer, resourceInstanceAttribute, resourceInstanceId, errorWrapper);
if (errorWrapper.isEmpty()) {
AttributeValueData attributeValueData = updateDataContainer.getValueDataWrapper().getInnerElement();
attributeValueData.setHidden(resourceInstanceAttribute.isHidden());
attributeValueData.setValue(resourceInstanceAttribute.getValue());
-
- return janusGraphGenericDao.updateNode(
- attributeValueData, AttributeValueData.class
- );
+ return janusGraphGenericDao.updateNode(attributeValueData, AttributeValueData.class);
} else {
return Either.right(errorWrapper.getInnerElement());
}
}
- private Either<AttributeValueData, JanusGraphOperationStatus> addAttributeToResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId, Integer index) {
+ private Either<AttributeValueData, JanusGraphOperationStatus> addAttributeToResourceInstance(ComponentInstanceProperty attributeInstanceProperty,
+ String resourceInstanceId, Integer index) {
Wrapper<JanusGraphOperationStatus> errorWrapper = new Wrapper<>();
Wrapper<ComponentInstanceData> compInsWrapper = new Wrapper<>();
Wrapper<AttributeData> attDataWrapper = new Wrapper<>();
Wrapper<AttributeValueData> attValueDataWrapper = new Wrapper<>();
-
// Verify RI Exist
validateRIExist(resourceInstanceId, compInsWrapper, errorWrapper);
-
if (errorWrapper.isEmpty()) {
// Verify Attribute Exist
- validateElementExistInGraph(attributeInstanceProperty.getUniqueId(), NodeTypeEnum.Attribute, () -> AttributeData.class, attDataWrapper, errorWrapper);
+ validateElementExistInGraph(attributeInstanceProperty.getUniqueId(), NodeTypeEnum.Attribute, () -> AttributeData.class, attDataWrapper,
+ errorWrapper);
}
if (errorWrapper.isEmpty()) {
// Create AttributeValueData that is connected to RI
@@ -293,6 +232,7 @@ public class ComponentInstanceOperation extends AbstractOperation {
}
if (errorWrapper.isEmpty()) {
// Connect AttributeValueData (Att on RI) to AttData (Att on
+
// Resource)
connectAttValueDataToAttData(errorWrapper, attDataWrapper.getInnerElement(), attValueDataWrapper.getInnerElement());
}
@@ -300,65 +240,61 @@ public class ComponentInstanceOperation extends AbstractOperation {
// Connect AttributeValueData to RI
connectAttValueDataToComponentInstanceData(errorWrapper, compInsWrapper.getInnerElement(), attValueDataWrapper.getInnerElement());
}
-
if (errorWrapper.isEmpty()) {
return Either.left(attValueDataWrapper.getInnerElement());
} else {
return Either.right(errorWrapper.getInnerElement());
}
-
}
- private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
- String resourceInstanceId, Wrapper<JanusGraphOperationStatus> errorWrapper) {
-
+ private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(
+ UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
+ String resourceInstanceId, Wrapper<JanusGraphOperationStatus> errorWrapper) {
if (errorWrapper.isEmpty()) {
// Verify VFC instance Exist
validateRIExist(resourceInstanceId, errorWrapper);
}
-
if (errorWrapper.isEmpty()) {
// Example: Verify Property connected to VFC exist
validateElementConnectedToComponentExist(updateDataContainer, resourceInstanceProerty, errorWrapper);
}
-
if (errorWrapper.isEmpty()) {
// Example: Verify PropertyValue connected to VFC Instance exist
validateElementConnectedToComponentInstanceExist(updateDataContainer, resourceInstanceProerty, errorWrapper);
}
-
if (errorWrapper.isEmpty()) {
// Example: Verify PropertyValue connected Property
validateElementConnectedToInstance(updateDataContainer, resourceInstanceProerty, errorWrapper);
}
}
- private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToInstance(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
- Wrapper<JanusGraphOperationStatus> errorWrapper) {
+ private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToInstance(
+ UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
+ Wrapper<JanusGraphOperationStatus> errorWrapper) {
Either<ImmutablePair<SomeData, GraphEdge>, JanusGraphOperationStatus> child = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(),
updateDataContainer.getGraphEdge(), updateDataContainer.getNodeType(), updateDataContainer.getSomeDataClassGen().get());
-
if (child.isRight()) {
JanusGraphOperationStatus status = child.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
status = JanusGraphOperationStatus.INVALID_ID;
}
errorWrapper.setInnerElement(status);
-
} else {
updateDataContainer.getDataWrapper().setInnerElement(child.left().value().left);
}
}
- private <SomeValueData extends GraphNode, SomeData extends GraphNode> void validateElementConnectedToComponentInstanceExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer,
- IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper<JanusGraphOperationStatus> errorWrapper) {
+ private <SomeValueData extends GraphNode, SomeData extends GraphNode> void validateElementConnectedToComponentInstanceExist(
+ UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
+ Wrapper<JanusGraphOperationStatus> errorWrapper) {
String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid();
if (valueUniqueUid == null) {
errorWrapper.setInnerElement(JanusGraphOperationStatus.INVALID_ID);
} else {
Either<SomeValueData, JanusGraphOperationStatus> findPropertyValueRes = janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid, updateDataContainer.getSomeValueDataClassGen().get());
+ .getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid,
+ updateDataContainer.getSomeValueDataClassGen().get());
if (findPropertyValueRes.isRight()) {
JanusGraphOperationStatus status = findPropertyValueRes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -371,12 +307,12 @@ public class ComponentInstanceOperation extends AbstractOperation {
}
}
- private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToComponentExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer,
- IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper<JanusGraphOperationStatus> errorWrapper) {
+ private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToComponentExist(
+ UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceElementConnected,
+ Wrapper<JanusGraphOperationStatus> errorWrapper) {
String uniqueId = resourceInstanceElementConnected.getUniqueId();
Either<SomeData, JanusGraphOperationStatus> findPropertyDefRes = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get());
-
if (findPropertyDefRes.isRight()) {
JanusGraphOperationStatus status = findPropertyDefRes.right().value();
errorWrapper.setInnerElement(status);
@@ -387,12 +323,16 @@ public class ComponentInstanceOperation extends AbstractOperation {
validateRIExist(resourceInstanceId, null, errorWrapper);
}
- private void validateRIExist(String resourceInstanceId, Wrapper<ComponentInstanceData> compInsDataWrapper, Wrapper<JanusGraphOperationStatus> errorWrapper) {
- validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.ResourceInstance, () -> ComponentInstanceData.class, compInsDataWrapper, errorWrapper);
+ private void validateRIExist(String resourceInstanceId, Wrapper<ComponentInstanceData> compInsDataWrapper,
+ Wrapper<JanusGraphOperationStatus> errorWrapper) {
+ validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.ResourceInstance, () -> ComponentInstanceData.class, compInsDataWrapper,
+ errorWrapper);
}
- public <ElementData extends GraphNode> void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType, Supplier<Class<ElementData>> elementClassGen, Wrapper<ElementData> elementDataWrapper,
- Wrapper<JanusGraphOperationStatus> errorWrapper) {
+ public <ElementData extends GraphNode> void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType,
+ Supplier<Class<ElementData>> elementClassGen,
+ Wrapper<ElementData> elementDataWrapper,
+ Wrapper<JanusGraphOperationStatus> errorWrapper) {
Either<ElementData, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(elementNodeType), elementUniqueId, elementClassGen.get());
if (findResInstanceRes.isRight()) {
@@ -415,11 +355,10 @@ public class ComponentInstanceOperation extends AbstractOperation {
* @param index
* @return
*/
- private Either<InputValueData, JanusGraphOperationStatus> addInputToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index) {
-
+ private Either<InputValueData, JanusGraphOperationStatus> addInputToResourceInstance(ComponentInstanceInput resourceInstanceInput,
+ String resourceInstanceId, Integer index) {
Either<ComponentInstanceData, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class);
-
if (findResInstanceRes.isRight()) {
JanusGraphOperationStatus status = findResInstanceRes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -427,11 +366,9 @@ public class ComponentInstanceOperation extends AbstractOperation {
}
return Either.right(status);
}
-
String propertyId = resourceInstanceInput.getUniqueId();
Either<InputsData, JanusGraphOperationStatus> findPropertyDefRes = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), propertyId, InputsData.class);
-
if (findPropertyDefRes.isRight()) {
JanusGraphOperationStatus status = findPropertyDefRes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -439,32 +376,24 @@ public class ComponentInstanceOperation extends AbstractOperation {
}
return Either.right(status);
}
-
String valueUniqueUid = resourceInstanceInput.getValueUniqueUid();
if (valueUniqueUid == null) {
-
InputsData propertyData = findPropertyDefRes.left().value();
-
ComponentInstanceData resourceInstanceData = findResInstanceRes.left().value();
-
ImmutablePair<JanusGraphOperationStatus, String> isInputValueExists = inputOperation.findInputValue(resourceInstanceId, propertyId);
if (isInputValueExists.getLeft() == JanusGraphOperationStatus.ALREADY_EXIST) {
log.debug("The property {} already added to the resource instance {}", propertyId, resourceInstanceId);
resourceInstanceInput.setValueUniqueUid(isInputValueExists.getRight());
}
-
if (isInputValueExists.getLeft() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("After finding input value of {} on componenet instance {}", propertyId, resourceInstanceId);
return Either.right(isInputValueExists.getLeft());
}
-
String innerType = null;
-
PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
String propertyType = propDataDef.getType();
String value = resourceInstanceInput.getValue();
ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
-
if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
SchemaDefinition def = propDataDef.getSchema();
if (def == null) {
@@ -478,113 +407,97 @@ public class ComponentInstanceOperation extends AbstractOperation {
}
innerType = propDef.getType();
}
-
log.debug("Before validateAndUpdatePropertyValue");
Either<Map<String, DataTypeDefinition>, 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);
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
+ "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
return Either.right(status);
}
-
String uniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(resourceInstanceData.getUniqueId(), index);
InputValueData propertyValueData = new InputValueData();
propertyValueData.setUniqueId(uniqueId);
propertyValueData.setValue(value);
-
log.debug("Before validateAndUpdateRules");
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceInput.getRules(), innerType, allDataTypes.left().value(), true);
+ ImmutablePair<String, Boolean> pair = propertyOperation
+ .validateAndUpdateRules(propertyType, resourceInstanceInput.getRules(), innerType, allDataTypes.left().value(), true);
log.debug("After validateAndUpdateRules. pair = {} ", pair);
if (pair.getRight() != null && !pair.getRight()) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceInput.getName(), propertyType);
+ BeEcompErrorManager.getInstance()
+ .logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceInput.getName(), propertyType);
return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT);
}
log.debug("Before adding property value to graph {}", propertyValueData);
Either<InputValueData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
.createNode(propertyValueData, InputValueData.class);
log.debug("After adding property value to graph {}", propertyValueData);
-
if (createNodeResult.isRight()) {
JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
return Either.right(operationStatus);
}
-
Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
.createRelation(propertyValueData, propertyData, GraphEdgeLabels.INPUT_IMPL, null);
-
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createRelResult.right().value();
log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
return Either.right(operationStatus);
}
-
Map<String, Object> properties1 = new HashMap<>();
-
properties1.put(GraphEdgePropertiesDictionary.NAME.getProperty(), resourceInstanceData.getComponentInstDataDefinition().getName());
- properties1.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), resourceInstanceData.getComponentInstDataDefinition().getUniqueId());
-
- createRelResult = janusGraphGenericDao
- .createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.INPUT_VALUE, properties1);
-
+ properties1
+ .put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), resourceInstanceData.getComponentInstDataDefinition().getUniqueId());
+ createRelResult = janusGraphGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.INPUT_VALUE, properties1);
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, operationStatus);
+ log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId,
+ operationStatus);
return Either.right(operationStatus);
-
}
-
return Either.left(createNodeResult.left().value());
} else {
log.error("property value already exists.");
return Either.right(JanusGraphOperationStatus.ALREADY_EXIST);
}
-
}
- public Either<ComponentInstanceProperty, StorageOperationStatus> addAttributeValueToResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction) {
+ public Either<ComponentInstanceProperty, StorageOperationStatus> addAttributeValueToResourceInstance(
+ ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction) {
Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
-
try {
-
- Either<AttributeValueData, JanusGraphOperationStatus> eitherStatus = this.addAttributeToResourceInstance(resourceInstanceAttribute, resourceInstanceId, index);
-
+ Either<AttributeValueData, JanusGraphOperationStatus> eitherStatus = this
+ .addAttributeToResourceInstance(resourceInstanceAttribute, resourceInstanceId, index);
if (eitherStatus.isRight()) {
- log.error("Failed to add attribute value {} to resource instance {} in Graph. status is {}", resourceInstanceAttribute, resourceInstanceId, eitherStatus.right().value().name());
+ log.error("Failed to add attribute value {} to resource instance {} in Graph. status is {}", resourceInstanceAttribute,
+ resourceInstanceId, eitherStatus.right().value().name());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
return result;
} else {
AttributeValueData attributeValueData = eitherStatus.left().value();
-
ComponentInstanceProperty attributeValueResult = buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute);
log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult);
-
result = Either.left(attributeValueResult);
return result;
}
- }
-
- finally {
+ } finally {
handleTransactionCommitRollback(inTransaction, result);
}
}
- private ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceProperty resourceInstanceAttribute) {
+ private ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData,
+ ComponentInstanceProperty resourceInstanceAttribute) {
Boolean hidden = attributeValueData.isHidden();
String uid = attributeValueData.getUniqueId();
return new ComponentInstanceProperty(hidden, resourceInstanceAttribute, uid);
}
public Either<ComponentInstanceProperty, StorageOperationStatus> updateAttributeValueInResourceInstance(
- ComponentInstanceProperty resourceInstanceAttribute,
- String resourceInstanceId,
- boolean inTransaction
- ) {
+ ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, boolean inTransaction) {
//TODO This null could bubble up. Shouldn't we set a default value (such as Either.left(StorageOperationStatus.GENERAL_ERROR)) ?
Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
try {
result = updateAttributeOfResourceInstance(resourceInstanceAttribute, resourceInstanceId)
- .bimap(
- buildResourceInstanceAttribute(resourceInstanceAttribute),
+ .bimap(buildResourceInstanceAttribute(resourceInstanceAttribute),
handleFailedAttributeAdditionError(resourceInstanceAttribute, resourceInstanceId));
} finally {
handleTransactionCommitRollback(inTransaction, result);
@@ -595,47 +508,46 @@ public class ComponentInstanceOperation extends AbstractOperation {
private F<JanusGraphOperationStatus, StorageOperationStatus> handleFailedAttributeAdditionError(
ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId) {
return status -> {
- log.error("Failed to add attribute value {} to resource instance {} in Graph. status is {}",
- resourceInstanceAttribute, resourceInstanceId, status.name());
+ log.error("Failed to add attribute value {} to resource instance {} in Graph. status is {}", resourceInstanceAttribute,
+ resourceInstanceId, status.name());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
};
}
- private F<AttributeValueData, ComponentInstanceProperty> buildResourceInstanceAttribute(
- ComponentInstanceProperty resourceInstanceAttribute) {
+ private F<AttributeValueData, ComponentInstanceProperty> buildResourceInstanceAttribute(ComponentInstanceProperty resourceInstanceAttribute) {
return attributeValueData -> {
- ComponentInstanceProperty attributeValueResult =
- buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute);
+ ComponentInstanceProperty attributeValueResult = buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute);
log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult);
return attributeValueResult;
};
}
- public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index, boolean inTransaction) {
-
+ public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance(ComponentInstanceInput resourceInstanceInput,
+ String resourceInstanceId, Integer index,
+ boolean inTransaction) {
/// #RULES SUPPORT
+
/// Ignore rules received from client till support
resourceInstanceInput.setRules(null);
///
- ///
+ ///
Either<ComponentInstanceInput, StorageOperationStatus> result = null;
-
try {
-
- Either<InputValueData, JanusGraphOperationStatus> eitherStatus = addInputToResourceInstance(resourceInstanceInput, resourceInstanceId, index);
-
+ Either<InputValueData, JanusGraphOperationStatus> eitherStatus = addInputToResourceInstance(resourceInstanceInput, resourceInstanceId,
+ index);
if (eitherStatus.isRight()) {
- log.error("Failed to add input value {} to resource instance {} in Graph. status is {}", resourceInstanceInput, resourceInstanceId, eitherStatus.right().value().name());
+ log.error("Failed to add input value {} to resource instance {} in Graph. status is {}", resourceInstanceInput, resourceInstanceId,
+ eitherStatus.right().value().name());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
return result;
} else {
InputValueData propertyValueData = eitherStatus.left().value();
-
ComponentInstanceInput propertyValueResult = inputOperation.buildResourceInstanceInput(propertyValueData, resourceInstanceInput);
log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
-
- Either<String, JanusGraphOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceInput.getPath(), resourceInstanceInput.getUniqueId(), resourceInstanceInput.getDefaultValue());
+ Either<String, JanusGraphOperationStatus> findDefaultValue = propertyOperation
+ .findDefaultValueFromSecondPosition(resourceInstanceInput.getPath(), resourceInstanceInput.getUniqueId(),
+ resourceInstanceInput.getDefaultValue());
if (findDefaultValue.isRight()) {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findDefaultValue.right().value()));
return result;
@@ -643,13 +555,10 @@ public class ComponentInstanceOperation extends AbstractOperation {
String defaultValue = findDefaultValue.left().value();
propertyValueResult.setDefaultValue(defaultValue);
log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
-
result = Either.left(propertyValueResult);
return result;
}
- }
-
- finally {
+ } finally {
if (!inTransaction) {
if (result == null || result.isRight()) {
log.error("Going to execute rollback on graph.");
@@ -660,15 +569,16 @@ public class ComponentInstanceOperation extends AbstractOperation {
}
}
}
-
}
- public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b) {
+ public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input,
+ String resourceInstanceId, boolean b) {
return null;
}
public StorageOperationStatus updateCustomizationUUID(String componentInstanceId) {
- Either<JanusGraphVertex, JanusGraphOperationStatus> vertexByProperty = janusGraphGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId);
+ Either<JanusGraphVertex, JanusGraphOperationStatus> vertexByProperty = janusGraphGenericDao
+ .getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId);
if (vertexByProperty.isRight()) {
log.debug("Failed to fetch component instance by id {} error {}", componentInstanceId, vertexByProperty.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexByProperty.right().value());
@@ -676,15 +586,14 @@ public class ComponentInstanceOperation extends AbstractOperation {
UUID uuid = UUID.randomUUID();
JanusGraphVertex ciVertex = vertexByProperty.left().value();
ciVertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString());
-
return StorageOperationStatus.OK;
}
- public Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
-
+ public Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(
+ ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
log.debug("Going to update modification time of component instance {}. ", componentInstance.getName());
Either<ComponentInstanceData, StorageOperationStatus> result = null;
- try{
+ try {
ComponentInstanceData componentData = new ComponentInstanceData(componentInstance, componentInstance.getGroupInstances().size());
componentData.getComponentInstDataDefinition().setModificationTime(modificationTime);
componentData.getComponentInstDataDefinition().setCustomizationUUID(UUID.randomUUID().toString());
@@ -693,14 +602,15 @@ public class ComponentInstanceOperation extends AbstractOperation {
if (updateNode.isRight()) {
log.error("Failed to update resource {}. status is {}", componentInstance.getUniqueId(), updateNode.right().value());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateNode.right().value()));
- }else{
+ } else {
result = Either.left(updateNode.left().value());
}
- }catch(Exception e){
- log.error("Exception occured during update modification date of compomemt instance{}. The message is {}. ", componentInstance.getName(), e.getMessage(), e);
+ } catch (Exception e) {
+ log.error("Exception occured during update modification date of compomemt instance{}. The message is {}. ", componentInstance.getName(),
+ e.getMessage(), e);
result = Either.right(StorageOperationStatus.GENERAL_ERROR);
- }finally {
- if(!inTransaction){
+ } finally {
+ if (!inTransaction) {
if (result == null || result.isRight()) {
log.error("Going to execute rollback on graph.");
janusGraphGenericDao.rollback();
@@ -712,4 +622,55 @@ public class ComponentInstanceOperation extends AbstractOperation {
}
return result;
}
+
+ private static final class UpdateDataContainer<SomeData, SomeValueData> {
+
+ final Wrapper<SomeValueData> valueDataWrapper;
+ final Wrapper<SomeData> dataWrapper;
+ final GraphEdgeLabels graphEdge;
+ final Supplier<Class<SomeData>> someDataClassGen;
+ final Supplier<Class<SomeValueData>> someValueDataClassGen;
+ final NodeTypeEnum nodeType;
+ final NodeTypeEnum nodeTypeValue;
+
+ private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier<Class<SomeData>> someDataClassGen,
+ Supplier<Class<SomeValueData>> someValueDataClassGen, NodeTypeEnum nodeType, NodeTypeEnum nodeTypeValue) {
+ super();
+ this.valueDataWrapper = new Wrapper<>();
+ this.dataWrapper = new Wrapper<>();
+ this.graphEdge = graphEdge;
+ this.someDataClassGen = someDataClassGen;
+ this.someValueDataClassGen = someValueDataClassGen;
+ this.nodeType = nodeType;
+ this.nodeTypeValue = nodeTypeValue;
+ }
+
+ public Wrapper<SomeValueData> getValueDataWrapper() {
+ return valueDataWrapper;
+ }
+
+ public Wrapper<SomeData> getDataWrapper() {
+ return dataWrapper;
+ }
+
+ public GraphEdgeLabels getGraphEdge() {
+ return graphEdge;
+ }
+
+ public Supplier<Class<SomeData>> getSomeDataClassGen() {
+ return someDataClassGen;
+ }
+
+ public Supplier<Class<SomeValueData>> getSomeValueDataClassGen() {
+ return someValueDataClassGen;
+ }
+
+ public NodeTypeEnum getNodeType() {
+ return nodeType;
+ }
+
+ public NodeTypeEnum getNodeTypeValue() {
+ return nodeTypeValue;
+ }
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java
index 4da2cb4d40..94ba3d8c53 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import fj.data.Either;
+import java.util.Collections;
+import java.util.List;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
@@ -32,18 +33,13 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
-import java.util.Collections;
-import java.util.List;
-
@Component("consumer-operation")
public class ConsumerOperation implements IConsumerOperation {
- private JanusGraphGenericDao janusGraphGenericDao;
-
private static final Logger log = Logger.getLogger(ConsumerOperation.class.getName());
+ private JanusGraphGenericDao janusGraphGenericDao;
- public ConsumerOperation(@Qualifier("janusgraph-generic-dao")
- JanusGraphGenericDao janusGraphGenericDao) {
+ public ConsumerOperation(@Qualifier("janusgraph-generic-dao") JanusGraphGenericDao janusGraphGenericDao) {
this.janusGraphGenericDao = janusGraphGenericDao;
}
@@ -66,9 +62,8 @@ public class ConsumerOperation implements IConsumerOperation {
@Override
public Either<List<ConsumerData>, StorageOperationStatus> getAll() {
log.debug("retrieving all consumers");
- return janusGraphGenericDao
- .getByCriteria(NodeTypeEnum.ConsumerCredentials, Collections.emptyMap(), ConsumerData.class)
- .right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ return janusGraphGenericDao.getByCriteria(NodeTypeEnum.ConsumerCredentials, Collections.emptyMap(), ConsumerData.class).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
@Override
@@ -81,8 +76,7 @@ public class ConsumerOperation implements IConsumerOperation {
Either<ConsumerData, StorageOperationStatus> result = null;
try {
log.debug("creating Credentials for: {}", consumerData.getUniqueId());
- Either<ConsumerData, JanusGraphOperationStatus> createNode = janusGraphGenericDao
- .createNode(consumerData, ConsumerData.class);
+ Either<ConsumerData, JanusGraphOperationStatus> createNode = janusGraphGenericDao.createNode(consumerData, ConsumerData.class);
if (createNode.isRight()) {
JanusGraphOperationStatus status = createNode.right().value();
log.error("Error returned after creating Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status);
@@ -115,14 +109,12 @@ public class ConsumerOperation implements IConsumerOperation {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
return result;
}
-
ConsumerData deletedConsumerData = deleteNode.left().value();
result = Either.left(deletedConsumerData);
return result;
} finally {
handleTransaction(inTransaction, result);
}
-
}
@Override
@@ -132,12 +124,10 @@ public class ConsumerOperation implements IConsumerOperation {
@Override
public Either<ConsumerData, StorageOperationStatus> updateCredentials(ConsumerData consumerData, boolean inTransaction) {
-
Either<ConsumerData, StorageOperationStatus> result = null;
try {
log.debug("update Credentials for: {}", consumerData.getUniqueId());
- Either<ConsumerData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao
- .updateNode(consumerData, ConsumerData.class);
+ Either<ConsumerData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao.updateNode(consumerData, ConsumerData.class);
if (updateNode.isRight()) {
JanusGraphOperationStatus status = updateNode.right().value();
log.error("Error returned after delete Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status);
@@ -163,5 +153,4 @@ public class ConsumerOperation implements IConsumerOperation {
}
}
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java
index 0e88d6b081..7b40aa012c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import com.google.gson.Gson;
@@ -25,24 +24,21 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import fj.data.Either;
+import java.util.Map;
+import javax.annotation.PostConstruct;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import javax.annotation.PostConstruct;
-import java.util.Map;
-
@org.springframework.stereotype.Component("csar-operation")
public class CsarOperation {
private static final Logger log = Logger.getLogger(CsarOperation.class.getName());
-
@javax.annotation.Resource
private OnboardingClient onboardingClient;
@PostConstruct
public void init() {
-
}
/**
@@ -52,9 +48,7 @@ public class CsarOperation {
* @return
*/
public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, User user) {
-
Either<Map<String, byte[]>, StorageOperationStatus> result = onboardingClient.getCsar(csarUuid, user.getUserId());
-
if (result.isRight()) {
log.debug("Cannot find csar {}. Staus returned is {}", csarUuid, result.right().value());
} else {
@@ -63,15 +57,12 @@ public class CsarOperation {
log.debug("The returned files are {}", values.keySet());
}
}
-
return result;
}
@SuppressWarnings("unchecked")
public Either<String, StorageOperationStatus> getCsarLatestVersion(String csarUuid, User user) {
-
Either<String, StorageOperationStatus> result = onboardingClient.getPackages(user.getUserId());
-
if (result.isRight()) {
log.debug("Cannot find version for package with Id {}. Status returned is {}", csarUuid, result.right().value());
} else {
@@ -80,9 +71,9 @@ public class CsarOperation {
JsonArray csarsInfo = root.getAsJsonObject().get("results").getAsJsonArray();
for (JsonElement csarInfo : csarsInfo) {
Map<String, String> csarInfoMap = new Gson().fromJson(csarInfo, Map.class);
- if(csarInfoMap.get("packageId").equals(csarUuid)){
+ if (csarInfoMap.get("packageId").equals(csarUuid)) {
String curVersion = csarInfoMap.get("version");
- if(latestVersion == null || isGreater(latestVersion, curVersion)){
+ if (latestVersion == null || isGreater(latestVersion, curVersion)) {
latestVersion = curVersion;
}
}
@@ -94,7 +85,6 @@ public class CsarOperation {
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
-
return result;
}
@@ -105,5 +95,4 @@ public class CsarOperation {
public OnboardingClient getOnboardingClient() {
return onboardingClient;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java
index bce7a2a73c..14611ae4ad 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
@@ -27,53 +26,41 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
public class DaoStatusConverter {
public static StorageOperationStatus convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus janusGraphStatus) {
-
if (janusGraphStatus == null) {
return StorageOperationStatus.GENERAL_ERROR;
}
-
switch (janusGraphStatus) {
-
- case OK:
- return StorageOperationStatus.OK;
-
- case NOT_CONNECTED:
- return StorageOperationStatus.CONNECTION_FAILURE;
-
- case NOT_FOUND:
- return StorageOperationStatus.NOT_FOUND;
-
- case NOT_CREATED:
- return StorageOperationStatus.SCHEMA_ERROR;
-
- case INDEX_CANNOT_BE_CHANGED:
- return StorageOperationStatus.SCHEMA_ERROR;
-
- case MISSING_UNIQUE_ID:
- return StorageOperationStatus.BAD_REQUEST;
- case ALREADY_LOCKED:
- return StorageOperationStatus.FAILED_TO_LOCK_ELEMENT;
-
- case JANUSGRAPH_SCHEMA_VIOLATION:
- return StorageOperationStatus.SCHEMA_VIOLATION;
-
- case INVALID_ID:
- return StorageOperationStatus.INVALID_ID;
- case MATCH_NOT_FOUND:
- return StorageOperationStatus.MATCH_NOT_FOUND;
-
- case ILLEGAL_ARGUMENT:
- return StorageOperationStatus.BAD_REQUEST;
- case ALREADY_EXIST:
- return StorageOperationStatus.ENTITY_ALREADY_EXISTS;
- case PROPERTY_NAME_ALREADY_EXISTS:
- return StorageOperationStatus.PROPERTY_NAME_ALREADY_EXISTS;
- case INVALID_PROPERTY:
- return StorageOperationStatus.INVALID_PROPERTY;
- default:
- return StorageOperationStatus.GENERAL_ERROR;
+ case OK:
+ return StorageOperationStatus.OK;
+ case NOT_CONNECTED:
+ return StorageOperationStatus.CONNECTION_FAILURE;
+ case NOT_FOUND:
+ return StorageOperationStatus.NOT_FOUND;
+ case NOT_CREATED:
+ return StorageOperationStatus.SCHEMA_ERROR;
+ case INDEX_CANNOT_BE_CHANGED:
+ return StorageOperationStatus.SCHEMA_ERROR;
+ case MISSING_UNIQUE_ID:
+ return StorageOperationStatus.BAD_REQUEST;
+ case ALREADY_LOCKED:
+ return StorageOperationStatus.FAILED_TO_LOCK_ELEMENT;
+ case JANUSGRAPH_SCHEMA_VIOLATION:
+ return StorageOperationStatus.SCHEMA_VIOLATION;
+ case INVALID_ID:
+ return StorageOperationStatus.INVALID_ID;
+ case MATCH_NOT_FOUND:
+ return StorageOperationStatus.MATCH_NOT_FOUND;
+ case ILLEGAL_ARGUMENT:
+ return StorageOperationStatus.BAD_REQUEST;
+ case ALREADY_EXIST:
+ return StorageOperationStatus.ENTITY_ALREADY_EXISTS;
+ case PROPERTY_NAME_ALREADY_EXISTS:
+ return StorageOperationStatus.PROPERTY_NAME_ALREADY_EXISTS;
+ case INVALID_PROPERTY:
+ return StorageOperationStatus.INVALID_PROPERTY;
+ default:
+ return StorageOperationStatus.GENERAL_ERROR;
}
-
}
public static StorageOperationStatus convertCassandraStatusToStorageStatus(CassandraOperationStatus status) {
@@ -81,17 +68,16 @@ public class DaoStatusConverter {
return StorageOperationStatus.GENERAL_ERROR;
}
switch (status) {
- case OK:
- return StorageOperationStatus.OK;
- case CLUSTER_NOT_CONNECTED:
- return StorageOperationStatus.CONNECTION_FAILURE;
- case KEYSPACE_NOT_CONNECTED:
- return StorageOperationStatus.STORAGE_NOT_AVAILABLE;
- case NOT_FOUND:
- return StorageOperationStatus.NOT_FOUND;
-
- default:
- return StorageOperationStatus.GENERAL_ERROR;
+ case OK:
+ return StorageOperationStatus.OK;
+ case CLUSTER_NOT_CONNECTED:
+ return StorageOperationStatus.CONNECTION_FAILURE;
+ case KEYSPACE_NOT_CONNECTED:
+ return StorageOperationStatus.STORAGE_NOT_AVAILABLE;
+ case NOT_FOUND:
+ return StorageOperationStatus.NOT_FOUND;
+ default:
+ return StorageOperationStatus.GENERAL_ERROR;
}
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java
index c207965b46..ddf76209cd 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import fj.data.Either;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
@@ -38,9 +43,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.*;
-import java.util.function.Function;
-
@Component
public class DefaultDerivedFromOperation implements DerivedFromOperation {
@@ -53,80 +55,66 @@ public class DefaultDerivedFromOperation implements DerivedFromOperation {
}
@Override
- public Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(String parentUniqueId, String derivedFromUniqueId, NodeTypeEnum nodeType) {
+ public Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(String parentUniqueId, String derivedFromUniqueId,
+ NodeTypeEnum nodeType) {
UniqueIdData from = new UniqueIdData(nodeType, parentUniqueId);
UniqueIdData to = new UniqueIdData(nodeType, derivedFromUniqueId);
- return janusGraphGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ return janusGraphGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
@Override
public <T extends GraphNode> Either<T, StorageOperationStatus> getDerivedFromChild(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz) {
log.debug("#getDerivedFromChild - fetching derived from entity for node type {} with id {}", nodeType, uniqueId);
- return janusGraphGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz)
- .bimap(Pair::getKey,
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ return janusGraphGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz)
+ .bimap(Pair::getKey, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
@Override
public StorageOperationStatus removeDerivedFromRelation(String uniqueId, String derivedFromUniqueId, NodeTypeEnum nodeType) {
UniqueIdData from = new UniqueIdData(nodeType, uniqueId);
UniqueIdData to = new UniqueIdData(nodeType, derivedFromUniqueId);
- return isDerivedFromExists(from, to)
- .either(isRelationExist -> isRelationExist ? deleteDerivedFrom(from, to) : StorageOperationStatus.OK,
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
-
-
+ return isDerivedFromExists(from, to).either(isRelationExist -> isRelationExist ? deleteDerivedFrom(from, to) : StorageOperationStatus.OK,
+ DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
- private StorageOperationStatus deleteDerivedFrom(UniqueIdData from, UniqueIdData to) {
+ private StorageOperationStatus deleteDerivedFrom(UniqueIdData from, UniqueIdData to) {
return janusGraphGenericDao.deleteRelation(from, to, GraphEdgeLabels.DERIVED_FROM)
- .either(deletedRelation -> StorageOperationStatus.OK,
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .either(deletedRelation -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
private Either<Boolean, JanusGraphOperationStatus> isDerivedFromExists(UniqueIdData from, UniqueIdData to) {
return janusGraphGenericDao.isRelationExist(from, to, GraphEdgeLabels.DERIVED_FROM);
}
-
+
@Override
- public <T extends GraphNode> Either<Boolean, StorageOperationStatus> isTypeDerivedFrom(String childCandidateType, String parentCandidateType, String currentChildType,
- NodeTypeEnum nodeType, Class<T> clazz, Function<T, String> typeProvider) {
+ public <T extends GraphNode> Either<Boolean, StorageOperationStatus> isTypeDerivedFrom(String childCandidateType, String parentCandidateType,
+ String currentChildType, NodeTypeEnum nodeType,
+ Class<T> clazz, Function<T, String> typeProvider) {
Map<String, Object> propertiesToMatch = new HashMap<>();
propertiesToMatch.put(GraphPropertiesDictionary.TYPE.getProperty(), childCandidateType);
-
- Either<List<T>, JanusGraphOperationStatus> getResponse = janusGraphGenericDao
- .getByCriteria(nodeType, propertiesToMatch, clazz);
+ Either<List<T>, JanusGraphOperationStatus> getResponse = janusGraphGenericDao.getByCriteria(nodeType, propertiesToMatch, clazz);
if (getResponse.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = getResponse.right().value();
- log.debug("Couldn't fetch type {}, error: {}", childCandidateType,
- janusGraphOperationStatus);
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- janusGraphOperationStatus));
+ log.debug("Couldn't fetch type {}, error: {}", childCandidateType, janusGraphOperationStatus);
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
}
T node = getResponse.left().value().get(0);
String childUniqueId = node.getUniqueId();
String childType = typeProvider.apply(node);
-
Set<String> travelledTypes = new HashSet<>();
if (currentChildType != null) {
travelledTypes.add(currentChildType);
}
-
do {
travelledTypes.add(childType);
Either<List<ImmutablePair<T, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), childUniqueId, GraphEdgeLabels.DERIVED_FROM,
- nodeType, clazz);
+ .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), childUniqueId, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz);
if (childrenNodes.isRight()) {
if (childrenNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
JanusGraphOperationStatus janusGraphOperationStatus = getResponse.right().value();
- log.debug("Couldn't fetch derived from node for type {}, error: {}", childCandidateType,
- janusGraphOperationStatus);
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- janusGraphOperationStatus));
+ log.debug("Couldn't fetch derived from node for type {}, error: {}", childCandidateType, janusGraphOperationStatus);
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
} else {
log.debug("Derived from node is not found for type {} - this is OK for root capability.", childCandidateType);
return Either.left(false);
@@ -142,44 +130,41 @@ public class DefaultDerivedFromOperation implements DerivedFromOperation {
childType = derivedFromType;
} while (!travelledTypes.contains(childType));
// this stop condition should never be used, if we use it, we have an
+
// illegal cycle in graph - "derived from" hierarchy cannot be cycled.
+
// It's here just to avoid infinite loop in case we have such cycle.
log.error("Detected a cycle of \"derived from\" edges starting at type node {}", childType);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
-
-
-
+
@Override
public <T extends GraphNode> StorageOperationStatus isUpdateParentAllowed(String oldTypeParent, String newTypeParent, String childType,
NodeTypeEnum nodeType, Class<T> clazz,
Function<T, String> typeProvider) {
StorageOperationStatus status;
if (oldTypeParent != null) {
-
- Either<Boolean, StorageOperationStatus> result = isTypeDerivedFrom(newTypeParent, oldTypeParent, childType, nodeType, clazz, typeProvider);
+ Either<Boolean, StorageOperationStatus> result = isTypeDerivedFrom(newTypeParent, oldTypeParent, childType, nodeType, clazz,
+ typeProvider);
if (result.isRight()) {
- log.debug("#isUpdateParentAllowed - failed to detect that new parent {} is derived from the current parent {}", newTypeParent, oldTypeParent);
+ log.debug("#isUpdateParentAllowed - failed to detect that new parent {} is derived from the current parent {}", newTypeParent,
+ oldTypeParent);
status = result.right().value();
- }
- else {
+ } else {
if (result.left().value()) {
- log.debug("#isUpdateParentAllowed - update is allowed since new parent {} is derived from the current parent {}", newTypeParent, oldTypeParent);
+ log.debug("#isUpdateParentAllowed - update is allowed since new parent {} is derived from the current parent {}", newTypeParent,
+ oldTypeParent);
status = StorageOperationStatus.OK;
- }
- else {
- log.debug("#isUpdateParentAllowed - update is not allowed since new parent {} is not derived from the current parent {}", newTypeParent, oldTypeParent);
+ } else {
+ log.debug("#isUpdateParentAllowed - update is not allowed since new parent {} is not derived from the current parent {}",
+ newTypeParent, oldTypeParent);
status = StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY;
}
}
-
- }
- else {
- log.debug("#isUpdateParentAllowed - the update is allowed since the parent still has been not set." );
+ } else {
+ log.debug("#isUpdateParentAllowed - the update is allowed since the parent still has been not set.");
status = StorageOperationStatus.OK;
}
-
return status;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java
index b536f166c3..60ffa1b0f7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import fj.data.Either;
@@ -69,16 +68,32 @@ import org.springframework.stereotype.Component;
public class ElementOperation implements IElementOperation {
private static final String COULDN_T_FETCH_janusGraph_GRAPH = "Couldn't fetch janusgraph graph";
- private static final String UNKNOWN_CATEGORY_TYPE = "Unknown category type {}";
- private JanusGraphGenericDao janusGraphGenericDao;
+ private static final String UNKNOWN_CATEGORY_TYPE = "Unknown category type {}";
+ private static final Logger log = Logger.getLogger(ElementOperation.class.getName());
+ private JanusGraphGenericDao janusGraphGenericDao;
- public ElementOperation(@Qualifier("janusgraph-generic-dao")
- JanusGraphGenericDao janusGraphGenericDao) {
+ public ElementOperation(@Qualifier("janusgraph-generic-dao") JanusGraphGenericDao janusGraphGenericDao) {
super();
this.janusGraphGenericDao = janusGraphGenericDao;
}
- private static final Logger log = Logger.getLogger(ElementOperation.class.getName());
+ private static NodeTypeEnum getChildNodeType(NodeTypeEnum parentTypeEnum) {
+ NodeTypeEnum res = null;
+ switch (parentTypeEnum) {
+ case ResourceNewCategory:
+ res = NodeTypeEnum.ResourceSubcategory;
+ break;
+ case ProductCategory:
+ res = NodeTypeEnum.ProductSubcategory;
+ break;
+ case ProductSubcategory:
+ res = NodeTypeEnum.ProductGrouping;
+ break;
+ default:
+ break;
+ }
+ return res;
+ }
/*
* Old flow
@@ -97,9 +112,6 @@ public class ElementOperation implements IElementOperation {
public Either<List<CategoryDefinition>, ActionStatus> getAllProductCategories() {
return getAllCategories(NodeTypeEnum.ProductCategory, false);
}
- /*
- *
- */
/*
* New flow
@@ -114,10 +126,8 @@ public class ElementOperation implements IElementOperation {
Either<CategoryDefinition, ActionStatus> result = null;
category.setUniqueId(UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeType));
CategoryData categoryData = new CategoryData(nodeType, category);
-
try {
- Either<CategoryData, JanusGraphOperationStatus> createNode = janusGraphGenericDao
- .createNode(categoryData, CategoryData.class);
+ Either<CategoryData, JanusGraphOperationStatus> createNode = janusGraphGenericDao.createNode(categoryData, CategoryData.class);
if (createNode.isRight()) {
JanusGraphOperationStatus value = createNode.right().value();
ActionStatus actionStatus = ActionStatus.GENERAL_ERROR;
@@ -141,7 +151,7 @@ public class ElementOperation implements IElementOperation {
}
}
}
-
+
@Override
public Either<CategoryDefinition, ActionStatus> updateCategory(CategoryDefinition category, NodeTypeEnum nodeType) {
return updateCategory(category, nodeType, false);
@@ -152,10 +162,8 @@ public class ElementOperation implements IElementOperation {
Either<CategoryDefinition, ActionStatus> result = null;
category.setUniqueId(UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeType));
CategoryData categoryData = new CategoryData(nodeType, category);
-
try {
- Either<CategoryData, JanusGraphOperationStatus> updatedNode = janusGraphGenericDao
- .updateNode(categoryData, CategoryData.class);
+ Either<CategoryData, JanusGraphOperationStatus> updatedNode = janusGraphGenericDao.updateNode(categoryData, CategoryData.class);
if (updatedNode.isRight()) {
JanusGraphOperationStatus value = updatedNode.right().value();
ActionStatus actionStatus = ActionStatus.GENERAL_ERROR;
@@ -178,15 +186,15 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) {
+ public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory,
+ NodeTypeEnum nodeType) {
return createSubCategory(categoryId, subCategory, nodeType, false);
}
@Override
- public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) {
-
+ public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType,
+ boolean inTransaction) {
Either<SubCategoryDefinition, ActionStatus> result = null;
-
try {
// create edge from category to sub-category
Either<CategoryData, JanusGraphOperationStatus> categoryNode = janusGraphGenericDao
@@ -201,14 +209,11 @@ public class ElementOperation implements IElementOperation {
result = Either.right(actionStatus);
return result;
}
-
CategoryDataDefinition categoryDataDefinition = categoryNode.left().value().getCategoryDataDefinition();
subCategory.setUniqueId(UniqueIdBuilder.buildSubCategoryUid(categoryDataDefinition.getUniqueId(), subCategory.getNormalizedName()));
SubCategoryData subCategoryData = new SubCategoryData(nodeType, subCategory);
-
Either<SubCategoryData, JanusGraphOperationStatus> subCategoryNode = janusGraphGenericDao
.createNode(subCategoryData, SubCategoryData.class);
-
if (subCategoryNode.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = subCategoryNode.right().value();
log.debug("Problem while creating category, reason {}", janusGraphOperationStatus);
@@ -218,7 +223,6 @@ public class ElementOperation implements IElementOperation {
result = Either.right(actionStatus);
return result;
}
-
Either<GraphRelation, JanusGraphOperationStatus> relation = janusGraphGenericDao
.createRelation(categoryNode.left().value(), subCategoryNode.left().value(), GraphEdgeLabels.SUB_CATEGORY, null);
if (relation.isRight()) {
@@ -226,7 +230,6 @@ public class ElementOperation implements IElementOperation {
result = Either.right(actionStatus);
return result;
}
-
SubCategoryDefinition subCategoryCreated = new SubCategoryDefinition(subCategoryNode.left().value().getSubCategoryDataDefinition());
result = Either.left(subCategoryCreated);
return result;
@@ -240,30 +243,28 @@ public class ElementOperation implements IElementOperation {
}
}
}
-
+
@Override
- public Either<SubCategoryDefinition, ActionStatus> updateSubCategory(String subCategoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) {
+ public Either<SubCategoryDefinition, ActionStatus> updateSubCategory(String subCategoryId, SubCategoryDefinition subCategory,
+ NodeTypeEnum nodeType) {
return updateSubCategory(subCategoryId, subCategory, nodeType, false);
}
@Override
- public Either<SubCategoryDefinition, ActionStatus> updateSubCategory(String subCategoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) {
-
+ public Either<SubCategoryDefinition, ActionStatus> updateSubCategory(String subCategoryId, SubCategoryDefinition subCategory,
+ NodeTypeEnum nodeType, boolean inTransaction) {
Either<SubCategoryDefinition, ActionStatus> result = null;
try {
subCategory.setUniqueId(subCategoryId);
SubCategoryData subCategoryData = new SubCategoryData(nodeType, subCategory);
-
Either<SubCategoryData, JanusGraphOperationStatus> subCategoryNode = janusGraphGenericDao
.updateNode(subCategoryData, SubCategoryData.class);
-
if (subCategoryNode.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = subCategoryNode.right().value();
log.debug("Problem while updating sub category, reason {}", janusGraphOperationStatus);
result = Either.right(ActionStatus.GENERAL_ERROR);
return result;
}
-
SubCategoryDefinition subCategoryUpdated = new SubCategoryDefinition(subCategoryNode.left().value().getSubCategoryDataDefinition());
result = Either.left(subCategoryUpdated);
return result;
@@ -280,9 +281,7 @@ public class ElementOperation implements IElementOperation {
@Override
public Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType) {
-
Either<GroupingDefinition, ActionStatus> result = null;
-
try {
// create edge from sub-category to grouping
Either<SubCategoryData, JanusGraphOperationStatus> subCategoryNode = janusGraphGenericDao
@@ -297,13 +296,10 @@ public class ElementOperation implements IElementOperation {
result = Either.right(actionStatus);
return result;
}
-
SubCategoryDataDefinition subCatData = subCategoryNode.left().value().getSubCategoryDataDefinition();
grouping.setUniqueId(UniqueIdBuilder.buildGroupingUid(subCatData.getUniqueId(), grouping.getNormalizedName()));
GroupingData groupingData = new GroupingData(nodeType, grouping);
-
- Either<GroupingData, JanusGraphOperationStatus> groupingNode = janusGraphGenericDao
- .createNode(groupingData, GroupingData.class);
+ Either<GroupingData, JanusGraphOperationStatus> groupingNode = janusGraphGenericDao.createNode(groupingData, GroupingData.class);
if (groupingNode.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = groupingNode.right().value();
log.debug("Problem while creating grouping, reason {}", janusGraphOperationStatus);
@@ -313,7 +309,6 @@ public class ElementOperation implements IElementOperation {
result = Either.right(actionStatus);
return result;
}
-
Either<GraphRelation, JanusGraphOperationStatus> relation = janusGraphGenericDao
.createRelation(subCategoryNode.left().value(), groupingNode.left().value(), GraphEdgeLabels.GROUPING, null);
if (relation.isRight()) {
@@ -336,11 +331,11 @@ public class ElementOperation implements IElementOperation {
@Override
public Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction) {
try {
- if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) {
+ if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory
+ && nodeType != NodeTypeEnum.ProductCategory) {
log.debug(UNKNOWN_CATEGORY_TYPE, nodeType.name());
return Either.right(ActionStatus.GENERAL_ERROR);
}
-
Either<List<org.openecomp.sdc.be.resources.data.category.CategoryData>, JanusGraphOperationStatus> either = janusGraphGenericDao
.getAll(nodeType, org.openecomp.sdc.be.resources.data.category.CategoryData.class);
if (either.isRight() && (either.right().value() != JanusGraphOperationStatus.NOT_FOUND)) {
@@ -352,14 +347,13 @@ public class ElementOperation implements IElementOperation {
if (categoryDataList != null) {
for (CategoryData elem : categoryDataList) {
CategoryDataDefinition categoryDataDefinition = elem.getCategoryDataDefinition();
-
CategoryDefinition categoryDefinition = new CategoryDefinition(categoryDataDefinition);
String categoryName = categoryDataDefinition.getName();
log.trace("Found category {}, category type {}", categoryName, nodeType);
- JanusGraphOperationStatus
- setSubCategories = setSubCategories(nodeType, categoryDefinition);
+ JanusGraphOperationStatus setSubCategories = setSubCategories(nodeType, categoryDefinition);
if (setSubCategories != JanusGraphOperationStatus.OK) {
- log.debug("Failed to set sub-categories for category {}, category type {}, error {}", categoryName, nodeType, setSubCategories);
+ log.debug("Failed to set sub-categories for category {}, category type {}, error {}", categoryName, nodeType,
+ setSubCategories);
return Either.right(ActionStatus.GENERAL_ERROR);
}
categoryList.add(categoryDefinition);
@@ -394,12 +388,12 @@ public class ElementOperation implements IElementOperation {
for (ImmutablePair<SubCategoryData, GraphEdge> subCatPair : subsCategoriesData) {
SubCategoryDataDefinition subCategoryDataDefinition = subCatPair.getLeft().getSubCategoryDataDefinition();
SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(subCategoryDataDefinition);
-
- log.trace("Found sub-category {} for category {}, category type {}", subCategoryDataDefinition.getName(), categoryName, parentNodeType);
- JanusGraphOperationStatus
- setGroupings = setGroupings(childNodeType, subCategoryDefinition);
+ log.trace("Found sub-category {} for category {}, category type {}", subCategoryDataDefinition.getName(), categoryName,
+ parentNodeType);
+ JanusGraphOperationStatus setGroupings = setGroupings(childNodeType, subCategoryDefinition);
if (setGroupings != JanusGraphOperationStatus.OK) {
- log.debug("Failed to set groupings for sub-category {}, sub-category type {}, error {}", subCategoryDataDefinition.getName(), childNodeType, setGroupings);
+ log.debug("Failed to set groupings for sub-category {}, sub-category type {}, error {}", subCategoryDataDefinition.getName(),
+ childNodeType, setGroupings);
return JanusGraphOperationStatus.GENERAL_ERROR;
}
subCategoriesDefinitions.add(subCategoryDefinition);
@@ -429,7 +423,8 @@ public class ElementOperation implements IElementOperation {
List<GroupingDefinition> groupingDefinitions = new ArrayList<>();
for (ImmutablePair<GroupingData, GraphEdge> groupPair : groupingData) {
GroupingDataDefinition groupingDataDefinition = groupPair.getLeft().getGroupingDataDefinition();
- log.trace("Found grouping {} for sub-category {}, sub-category type {}", groupingDataDefinition.getName(), subCategoryName, parentNodeType);
+ log.trace("Found grouping {} for sub-category {}, sub-category type {}", groupingDataDefinition.getName(), subCategoryName,
+ parentNodeType);
groupingDefinitions.add(new GroupingDefinition(groupingDataDefinition));
}
parentSubCategory.setGroupings(groupingDefinitions);
@@ -437,38 +432,19 @@ public class ElementOperation implements IElementOperation {
return JanusGraphOperationStatus.OK;
}
- private static NodeTypeEnum getChildNodeType(NodeTypeEnum parentTypeEnum) {
- NodeTypeEnum res = null;
- switch (parentTypeEnum) {
- case ResourceNewCategory:
- res = NodeTypeEnum.ResourceSubcategory;
- break;
- case ProductCategory:
- res = NodeTypeEnum.ProductSubcategory;
- break;
- case ProductSubcategory:
- res = NodeTypeEnum.ProductGrouping;
- break;
- default:
- break;
- }
- return res;
- }
-
@Override
public Either<CategoryDefinition, ActionStatus> getCategory(NodeTypeEnum nodeType, String categoryId) {
try {
- if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) {
+ if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory
+ && nodeType != NodeTypeEnum.ProductCategory) {
log.debug(UNKNOWN_CATEGORY_TYPE, nodeType.name());
return Either.right(ActionStatus.GENERAL_ERROR);
}
-
Either<CategoryData, JanusGraphOperationStatus> categoryDataEither = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class);
if (categoryDataEither.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = categoryDataEither.right().value();
- log.debug("Problem while get category by id {}. reason {}", categoryId,
- janusGraphOperationStatus);
+ log.debug("Problem while get category by id {}. reason {}", categoryId, janusGraphOperationStatus);
if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) {
return Either.right(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND);
}
@@ -488,13 +464,11 @@ public class ElementOperation implements IElementOperation {
log.debug("Unknown sub-category type {}", nodeType.name());
return Either.right(ActionStatus.GENERAL_ERROR);
}
-
Either<SubCategoryData, JanusGraphOperationStatus> subCategoryDataEither = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class);
if (subCategoryDataEither.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = subCategoryDataEither.right().value();
- log.debug("Problem while get sub-category by id {}. reason {}", subCategoryId,
- janusGraphOperationStatus);
+ log.debug("Problem while get sub-category by id {}. reason {}", subCategoryId, janusGraphOperationStatus);
if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) {
return Either.right(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND);
}
@@ -511,7 +485,8 @@ public class ElementOperation implements IElementOperation {
public Either<CategoryDefinition, ActionStatus> deleteCategory(NodeTypeEnum nodeType, String categoryId) {
Either<CategoryDefinition, ActionStatus> result = null;
try {
- if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) {
+ if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory
+ && nodeType != NodeTypeEnum.ProductCategory) {
log.debug(UNKNOWN_CATEGORY_TYPE, nodeType.name());
result = Either.right(ActionStatus.GENERAL_ERROR);
return result;
@@ -523,16 +498,13 @@ public class ElementOperation implements IElementOperation {
result = Either.right(ActionStatus.GENERAL_ERROR);
return result;
}
-
Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphGenericDao.getGraph();
if (graph.isRight()) {
log.debug(COULDN_T_FETCH_janusGraph_GRAPH);
result = Either.right(ActionStatus.GENERAL_ERROR);
return result;
}
-
JanusGraph tGraph = graph.left().value();
-
Iterable<JanusGraphVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId).vertices();
Iterator<JanusGraphVertex> iterator = verticesArtifact.iterator();
if (!iterator.hasNext()) {
@@ -570,16 +542,13 @@ public class ElementOperation implements IElementOperation {
result = Either.right(ActionStatus.GENERAL_ERROR);
return result;
}
-
Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphGenericDao.getGraph();
if (graph.isRight()) {
log.debug(COULDN_T_FETCH_janusGraph_GRAPH);
result = Either.right(ActionStatus.GENERAL_ERROR);
return result;
}
-
JanusGraph tGraph = graph.left().value();
-
Iterable<JanusGraphVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId).vertices();
Iterator<JanusGraphVertex> iterator = verticesArtifact.iterator();
if (!iterator.hasNext()) {
@@ -600,7 +569,6 @@ public class ElementOperation implements IElementOperation {
janusGraphGenericDao.rollback();
}
}
-
}
@Override
@@ -619,16 +587,13 @@ public class ElementOperation implements IElementOperation {
result = Either.right(ActionStatus.GENERAL_ERROR);
return result;
}
-
Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphGenericDao.getGraph();
if (graph.isRight()) {
log.debug(COULDN_T_FETCH_janusGraph_GRAPH);
result = Either.right(ActionStatus.GENERAL_ERROR);
return result;
}
-
JanusGraph tGraph = graph.left().value();
-
Iterable<JanusGraphVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId).vertices();
Iterator<JanusGraphVertex> iterator = verticesArtifact.iterator();
if (!iterator.hasNext()) {
@@ -653,14 +618,14 @@ public class ElementOperation implements IElementOperation {
@Override
public Either<Boolean, ActionStatus> isCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) {
-
Map<String, Object> properties = new HashMap<>();
properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName);
try {
Either<List<CategoryData>, JanusGraphOperationStatus> categoryEither = janusGraphGenericDao
.getByCriteria(nodeType, properties, CategoryData.class);
if (categoryEither.isRight() && categoryEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
- log.debug("Failed to get categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, categoryEither.right().value());
+ log.debug("Failed to get categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName,
+ categoryEither.right().value());
return Either.right(ActionStatus.GENERAL_ERROR);
}
List<CategoryData> categoryList = (categoryEither.isLeft() ? categoryEither.left().value() : null);
@@ -682,7 +647,6 @@ public class ElementOperation implements IElementOperation {
@Override
public Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId) {
-
String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(parentCategoryId, subCategoryNormName);
try {
Either<SubCategoryData, JanusGraphOperationStatus> subCategoryDataEither = janusGraphGenericDao
@@ -706,7 +670,6 @@ public class ElementOperation implements IElementOperation {
@Override
public Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId) {
-
String groupingId = UniqueIdBuilder.buildGroupingUid(parentSubCategoryId, groupingNormName);
try {
Either<GroupingData, JanusGraphOperationStatus> groupingDataEither = janusGraphGenericDao
@@ -736,7 +699,8 @@ public class ElementOperation implements IElementOperation {
Either<List<SubCategoryData>, JanusGraphOperationStatus> subCategoryEither = janusGraphGenericDao
.getByCriteria(nodeType, properties, SubCategoryData.class);
if (subCategoryEither.isRight() && subCategoryEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
- log.debug("Failed to get sub-categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, subCategoryEither.right().value());
+ log.debug("Failed to get sub-categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName,
+ subCategoryEither.right().value());
return Either.right(ActionStatus.GENERAL_ERROR);
}
List<SubCategoryData> subCategoryList = (subCategoryEither.isLeft() ? subCategoryEither.left().value() : null);
@@ -762,7 +726,8 @@ public class ElementOperation implements IElementOperation {
Either<List<GroupingData>, JanusGraphOperationStatus> groupingEither = janusGraphGenericDao
.getByCriteria(nodeType, properties, GroupingData.class);
if (groupingEither.isRight() && groupingEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
- log.debug("Failed to get grouping, nodeType {}, normalizedName {}, error {}", nodeType, groupingNormalizedName, groupingEither.right().value());
+ log.debug("Failed to get grouping, nodeType {}, normalizedName {}, error {}", nodeType, groupingNormalizedName,
+ groupingEither.right().value());
return Either.right(ActionStatus.GENERAL_ERROR);
}
List<GroupingData> groupingList = (groupingEither.isLeft() ? groupingEither.left().value() : null);
@@ -783,12 +748,10 @@ public class ElementOperation implements IElementOperation {
/*
*
*/
-
@Override
public Either<List<Tag>, ActionStatus> getAllTags() {
try {
- Either<List<TagData>, JanusGraphOperationStatus> either = janusGraphGenericDao
- .getAll(NodeTypeEnum.Tag, TagData.class);
+ Either<List<TagData>, JanusGraphOperationStatus> either = janusGraphGenericDao.getAll(NodeTypeEnum.Tag, TagData.class);
if (either.isRight()) {
log.debug("Problem while get all tags. reason - {}", either.right().value());
return Either.right(ActionStatus.GENERAL_ERROR);
@@ -802,7 +765,9 @@ public class ElementOperation implements IElementOperation {
}
@Override
- public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz) {
+ public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.CategoryData, StorageOperationStatus> getCategoryData(String name,
+ NodeTypeEnum type,
+ Class<T> clazz) {
if (name != null) {
String categoryUid = null;
if (type == NodeTypeEnum.ResourceCategory) {
@@ -814,13 +779,10 @@ public class ElementOperation implements IElementOperation {
} else {
categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type);
}
- Either<T, JanusGraphOperationStatus> either = janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(type), categoryUid, clazz);
-
+ Either<T, JanusGraphOperationStatus> either = janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(type), categoryUid, clazz);
if (either.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = either.right().value();
- log.debug("Problem while geting category with id {}. reason - {}", categoryUid, janusGraphOperationStatus
- .name());
+ log.debug("Problem while geting category with id {}. reason - {}", categoryUid, janusGraphOperationStatus.name());
if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) {
return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
} else {
@@ -882,7 +844,6 @@ public class ElementOperation implements IElementOperation {
for (int i = 0; i < enumConstants.length; ++i) {
resourceTypes.put(enumConstants[i].name(), enumConstants[i].getValue());
}
-
}
return Either.left(resourceTypes);
}
@@ -893,13 +854,10 @@ public class ElementOperation implements IElementOperation {
String categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type);
Map props = new HashMap<>();
props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(name));
- Either<List<T>, JanusGraphOperationStatus> either = janusGraphGenericDao
- .getByCriteria(type, props, clazz);
-
+ Either<List<T>, JanusGraphOperationStatus> either = janusGraphGenericDao.getByCriteria(type, props, clazz);
if (either.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = either.right().value();
- log.debug("Problem while geting category with id {}. reason - {}", categoryUid, janusGraphOperationStatus
- .name());
+ log.debug("Problem while geting category with id {}. reason - {}", categoryUid, janusGraphOperationStatus.name());
if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) {
return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
} else {
@@ -911,5 +869,4 @@ public class ElementOperation implements IElementOperation {
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java
index 009f375a13..0106cd3529 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
@@ -30,8 +29,8 @@ import org.springframework.stereotype.Component;
@Component("graph-lock-operation")
public class GraphLockOperation implements IGraphLockOperation {
- private static final Logger log = Logger.getLogger(GraphLockOperation.class.getName());
+ private static final Logger log = Logger.getLogger(GraphLockOperation.class.getName());
@javax.annotation.Resource
private JanusGraphGenericDao janusGraphGenericDao;
@@ -52,11 +51,8 @@ public class GraphLockOperation implements IGraphLockOperation {
lockElementStatus = janusGraphGenericDao.lockElement(componentId, nodeType);
} catch (Exception e) {
lockElementStatus = JanusGraphOperationStatus.ALREADY_LOCKED;
-
}
-
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(lockElementStatus);
-
}
/*
@@ -66,15 +62,13 @@ public class GraphLockOperation implements IGraphLockOperation {
*/
@Override
public StorageOperationStatus unlockComponent(String componentId, NodeTypeEnum nodeType) {
- JanusGraphOperationStatus lockElementStatus = janusGraphGenericDao
- .releaseElement(componentId, nodeType);
+ JanusGraphOperationStatus lockElementStatus = janusGraphGenericDao.releaseElement(componentId, nodeType);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(lockElementStatus);
}
@Override
public StorageOperationStatus unlockComponentByName(String name, String componentId, NodeTypeEnum nodeType) {
- JanusGraphOperationStatus
- lockElementStatus = janusGraphGenericDao.releaseElement(name, nodeType);
+ JanusGraphOperationStatus lockElementStatus = janusGraphGenericDao.releaseElement(name, nodeType);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(lockElementStatus);
}
@@ -83,15 +77,10 @@ public class GraphLockOperation implements IGraphLockOperation {
log.info("lock resource with name {}", name);
JanusGraphOperationStatus lockElementStatus = null;
try {
-
lockElementStatus = janusGraphGenericDao.lockElement(name, nodeType);
-
} catch (Exception e) {
lockElementStatus = JanusGraphOperationStatus.ALREADY_LOCKED;
-
}
-
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(lockElementStatus);
-
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java
index 6e980f20ba..45df37c4b8 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphVertex;
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.UUID;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphVertex;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
@@ -38,84 +45,79 @@ import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.GroupInstanceProperty;
+import org.openecomp.sdc.be.model.GroupProperty;
+import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
-import org.openecomp.sdc.be.resources.data.*;
+import org.openecomp.sdc.be.resources.data.ArtifactData;
+import org.openecomp.sdc.be.resources.data.GroupInstanceData;
+import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
+import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.*;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
@org.springframework.stereotype.Component("group-instance-operation")
public class GroupInstanceOperation extends AbstractOperation implements IGroupInstanceOperation {
private static final String UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE = "UpdatePropertyValueOnComponentInstance";
- private static final String FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS = "Failed to update property value on instance. Status is ";
- private static final Logger log = Logger.getLogger(GroupInstanceOperation.class.getName());
-
+ private static final String FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS = "Failed to update property value on instance. Status is ";
+ private static final Logger log = Logger.getLogger(GroupInstanceOperation.class.getName());
@Autowired
GroupOperation groupOperation;
-
@Autowired
PropertyOperation propertyOperation;
-
@javax.annotation.Resource
private ApplicationDataTypeCache dataTypeCache;
public Either<List<GroupInstance>, StorageOperationStatus> getAllGroupInstances(String parentId, NodeTypeEnum parentType) {
Either<List<GroupInstance>, StorageOperationStatus> result = null;
List<GroupInstance> groupInstanceRes = new ArrayList<>();
-
Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphGenericDao.getGraph();
if (graph.isRight()) {
log.debug("Failed to work with graph {}", graph.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graph.right().value()));
}
JanusGraph tGraph = graph.left().value();
- @SuppressWarnings("unchecked")
- Iterable<JanusGraphVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices();
+ @SuppressWarnings("unchecked") Iterable<JanusGraphVertex> vertices = tGraph.query()
+ .has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices();
if (vertices == null || vertices.iterator() == null || !vertices.iterator().hasNext()) {
log.debug("No nodes for type {} for id = {}", parentType, parentId);
result = Either.right(StorageOperationStatus.NOT_FOUND);
return result;
}
-
Iterator<JanusGraphVertex> iterator = vertices.iterator();
Vertex vertex = iterator.next();
-
Map<String, Object> edgeProperties = null;
-
Either<List<ImmutablePair<GroupInstanceData, GraphEdge>>, JanusGraphOperationStatus> childrenByEdgeCriteria = janusGraphGenericDao
- .getChildrenByEdgeCriteria(vertex, parentId, GraphEdgeLabels.GROUP_INST, NodeTypeEnum.GroupInstance,
- GroupInstanceData.class, edgeProperties);
-
+ .getChildrenByEdgeCriteria(vertex, parentId, GraphEdgeLabels.GROUP_INST, NodeTypeEnum.GroupInstance, GroupInstanceData.class,
+ edgeProperties);
if (childrenByEdgeCriteria.isRight()) {
JanusGraphOperationStatus status = childrenByEdgeCriteria.right().value();
log.debug("Failed to find group instance {} on graph", childrenByEdgeCriteria.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
List<ImmutablePair<GroupInstanceData, GraphEdge>> list = childrenByEdgeCriteria.left().value();
-
for (ImmutablePair<GroupInstanceData, GraphEdge> pair : list) {
GroupInstanceData groupInstData = pair.getLeft();
GroupInstance groupInstance = new GroupInstance(groupInstData.getGroupDataDefinition());
String instOriginGroupId = groupInstance.getGroupUid();
Either<GroupDefinition, StorageOperationStatus> groupRes = groupOperation.getGroupFromGraph(instOriginGroupId, false, true, false);
-
if (groupRes.isRight()) {
return Either.right(groupRes.right().value());
}
-
GroupDefinition groupDefinition = groupRes.left().value();
- Either<Map<String, PropertyValueData>, JanusGraphOperationStatus> groupInstancePropertyValuesRes = getAllGroupInstancePropertyValuesData(groupInstData);
- if(groupInstancePropertyValuesRes.isRight()){
+ Either<Map<String, PropertyValueData>, JanusGraphOperationStatus> groupInstancePropertyValuesRes = getAllGroupInstancePropertyValuesData(
+ groupInstData);
+ if (groupInstancePropertyValuesRes.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(groupInstancePropertyValuesRes.right().value()));
}
buildGroupInstanceFromGroup(groupInstance, groupDefinition, groupInstancePropertyValuesRes.left().value());
@@ -129,7 +131,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
} else {
List<String> artifactsUid = new ArrayList<>();
List<String> artifactsUUID = new ArrayList<>();
-
List<ImmutablePair<String, String>> list1 = artifactsRes.left().value();
if (list != null) {
for (ImmutablePair<String, String> pair1 : list1) {
@@ -142,45 +143,44 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
groupInstance.setGroupInstanceArtifactsUuid(artifactsUUID);
}
}
-
groupInstanceRes.add(groupInstance);
log.debug("GroupInstance {} was added to list ", groupInstance.getUniqueId());
}
-
result = Either.left(groupInstanceRes);
return result;
-
}
-
public Either<Integer, StorageOperationStatus> increaseAndGetGroupInstancePropertyCounter(String instanceId) {
return propertyOperation.increaseAndGetObjInstancePropertyCounter(instanceId, NodeTypeEnum.GroupInstance);
}
- public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index, boolean inTransaction) {
+ public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty groupInstanceProperty,
+ String groupInstanceId, Integer index,
+ boolean inTransaction) {
/// #RULES SUPPORT
+
/// Ignore rules received from client till support
groupInstanceProperty.setRules(null);
///
- ///
+ ///
Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
-
try {
-
- Either<PropertyValueData, JanusGraphOperationStatus> eitherStatus = addPropertyToGroupInstance(groupInstanceProperty, groupInstanceId, index);
-
+ Either<PropertyValueData, JanusGraphOperationStatus> eitherStatus = addPropertyToGroupInstance(groupInstanceProperty, groupInstanceId,
+ index);
if (eitherStatus.isRight()) {
- log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", groupInstanceProperty, groupInstanceId, eitherStatus.right().value().name());
+ log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", groupInstanceProperty, groupInstanceId,
+ eitherStatus.right().value().name());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
return result;
} else {
PropertyValueData propertyValueData = eitherStatus.left().value();
-
- ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, groupInstanceProperty);
+ ComponentInstanceProperty propertyValueResult = propertyOperation
+ .buildResourceInstanceProperty(propertyValueData, groupInstanceProperty);
log.debug("The returned GroupInstanceProperty is {}", propertyValueResult);
-
- Either<String, JanusGraphOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(groupInstanceProperty.getPath(), groupInstanceProperty.getUniqueId(), groupInstanceProperty.getDefaultValue());
+ Either<String, JanusGraphOperationStatus> findDefaultValue = propertyOperation
+ .findDefaultValueFromSecondPosition(groupInstanceProperty.getPath(), groupInstanceProperty.getUniqueId(),
+ groupInstanceProperty.getDefaultValue());
if (findDefaultValue.isRight()) {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findDefaultValue.right().value()));
return result;
@@ -188,13 +188,10 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
String defaultValue = findDefaultValue.left().value();
propertyValueResult.setDefaultValue(defaultValue);
log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
-
result = Either.left(propertyValueResult);
return result;
}
- }
-
- finally {
+ } finally {
if (!inTransaction) {
if (result == null || result.isRight()) {
log.error("Going to execute rollback on graph.");
@@ -205,11 +202,12 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
}
}
-
}
- public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction) {
+ public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(
+ ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction) {
// TODO Auto-generated method stub
+
// change Propety class
return null;
}
@@ -225,11 +223,10 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
* @param index
* @return
*/
- public Either<PropertyValueData, JanusGraphOperationStatus> addPropertyToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index) {
-
+ public Either<PropertyValueData, JanusGraphOperationStatus> addPropertyToGroupInstance(ComponentInstanceProperty groupInstanceProperty,
+ String groupInstanceId, Integer index) {
Either<GroupInstanceData, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupInstanceId, GroupInstanceData.class);
-
if (findResInstanceRes.isRight()) {
JanusGraphOperationStatus status = findResInstanceRes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -237,11 +234,9 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
return Either.right(status);
}
-
String propertyId = groupInstanceProperty.getUniqueId();
Either<PropertyData, JanusGraphOperationStatus> findPropertyDefRes = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
-
if (findPropertyDefRes.isRight()) {
JanusGraphOperationStatus status = findPropertyDefRes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -249,37 +244,33 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
return Either.right(status);
}
-
String valueUniqueUid = groupInstanceProperty.getValueUniqueUid();
if (valueUniqueUid == null) {
-
PropertyData propertyData = findPropertyDefRes.left().value();
GroupInstanceData resourceInstanceData = findResInstanceRes.left().value();
-
ImmutablePair<JanusGraphOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(groupInstanceId, propertyId);
if (isPropertyValueExists.getLeft() == JanusGraphOperationStatus.ALREADY_EXIST) {
log.debug("The property {} already added to the resource instance {}", propertyId, groupInstanceId);
groupInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight());
- Either<PropertyValueData, JanusGraphOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(groupInstanceProperty, groupInstanceId);
+ Either<PropertyValueData, JanusGraphOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(
+ groupInstanceProperty, groupInstanceId);
if (updatePropertyOfResourceInstance.isRight()) {
- BeEcompErrorManager.getInstance().logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE, FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE,
+ FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + updatePropertyOfResourceInstance.right().value(),
+ ErrorSeverity.ERROR);
return Either.right(updatePropertyOfResourceInstance.right().value());
}
return Either.left(updatePropertyOfResourceInstance.left().value());
}
-
if (isPropertyValueExists.getLeft() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("After finding property value of {} on componenet instance {}", propertyId, groupInstanceId);
return Either.right(isPropertyValueExists.getLeft());
}
-
String innerType = null;
-
PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
String propertyType = propDataDef.getType();
String value = groupInstanceProperty.getValue();
ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
-
if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
SchemaDefinition def = propDataDef.getSchema();
if (def == null) {
@@ -293,17 +284,18 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
innerType = propDef.getType();
}
-
log.debug("Before validateAndUpdatePropertyValue");
Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
if (allDataTypes.isRight()) {
JanusGraphOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE, FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + status, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE, FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + status,
+ ErrorSeverity.ERROR);
return Either.right(status);
}
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
+ Either<Object, Boolean> isValid = propertyOperation
+ .validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
-
String newValue = value;
if (isValid.isRight()) {
Boolean res = isValid.right().value();
@@ -316,56 +308,48 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
newValue = object.toString();
}
}
-
String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(resourceInstanceData.getUniqueId(), index);
PropertyValueData propertyValueData = new PropertyValueData();
propertyValueData.setUniqueId(uniqueId);
propertyValueData.setValue(newValue);
-
log.debug("Before validateAndUpdateRules");
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProperty.getRules(), innerType, allDataTypes.left().value(), false);
+ ImmutablePair<String, Boolean> pair = propertyOperation
+ .validateAndUpdateRules(propertyType, groupInstanceProperty.getRules(), innerType, allDataTypes.left().value(), false);
log.debug("After validateAndUpdateRules. pair = {}", pair);
if (pair.getRight() != null && !pair.getRight()) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProperty.getName(), propertyType);
+ BeEcompErrorManager.getInstance()
+ .logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProperty.getName(), propertyType);
return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT);
}
propertyOperation.addRulesToNewPropertyValue(propertyValueData, groupInstanceProperty, groupInstanceId);
-
log.debug("Before adding property value to graph {}", propertyValueData);
Either<PropertyValueData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
.createNode(propertyValueData, PropertyValueData.class);
log.debug("After adding property value to graph {}", propertyValueData);
-
if (createNodeResult.isRight()) {
JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
return Either.right(operationStatus);
}
propertyValueData = createNodeResult.left().value();
-
Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
-
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createRelResult.right().value();
log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
return Either.right(operationStatus);
}
-
- createRelResult = janusGraphGenericDao
- .createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
-
+ createRelResult = janusGraphGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate resource instance {} property value {} in graph. status is {}", groupInstanceId, uniqueId, operationStatus);
+ log.error("Failed to associate resource instance {} property value {} in graph. status is {}", groupInstanceId, uniqueId,
+ operationStatus);
return Either.right(operationStatus);
}
-
return Either.left(propertyValueData);
} else {
log.error("property value already exists.");
return Either.right(JanusGraphOperationStatus.ALREADY_EXIST);
}
-
}
/**
@@ -373,29 +357,23 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
*
* @return
*/
- public Either<PropertyValueData, JanusGraphOperationStatus> updatePropertyOfGroupInstance(ComponentInstanceProperty groupInstanceProerty, String groupInstanceId) {
-
+ public Either<PropertyValueData, JanusGraphOperationStatus> updatePropertyOfGroupInstance(ComponentInstanceProperty groupInstanceProerty,
+ String groupInstanceId) {
Wrapper<JanusGraphOperationStatus> errorWrapper = new Wrapper<>();
- UpdateDataContainer<PropertyData, PropertyValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.PROPERTY_IMPL, (() -> PropertyData.class), (() -> PropertyValueData.class), NodeTypeEnum.Property,
- NodeTypeEnum.PropertyValue);
-
+ UpdateDataContainer<PropertyData, PropertyValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.PROPERTY_IMPL,
+ (() -> PropertyData.class), (() -> PropertyValueData.class), NodeTypeEnum.Property, NodeTypeEnum.PropertyValue);
preUpdateElementOfResourceInstanceValidations(updateDataContainer, groupInstanceProerty, groupInstanceId, errorWrapper);
if (!errorWrapper.isEmpty()) {
return Either.right(errorWrapper.getInnerElement());
- }
-
- else {
+ } else {
String value = groupInstanceProerty.getValue();
// Specific Validation Logic
PropertyData propertyData = updateDataContainer.getDataWrapper().getInnerElement();
-
String innerType = null;
-
PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
String propertyType = propDataDef.getType();
ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
log.debug("The type of the property {} is {}", propertyData.getUniqueId(), propertyType);
-
if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
SchemaDefinition def = propDataDef.getSchema();
if (def == null) {
@@ -413,11 +391,13 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
if (allDataTypes.isRight()) {
JanusGraphOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE, FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + status, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE, FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + status,
+ ErrorSeverity.ERROR);
return Either.right(status);
}
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
-
+ Either<Object, Boolean> isValid = propertyOperation
+ .validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
String newValue = value;
if (isValid.isRight()) {
Boolean res = isValid.right().value();
@@ -433,14 +413,14 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
PropertyValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement();
log.debug("Going to update property value from {} to {}", propertyValueData.getValue(), newValue);
propertyValueData.setValue(newValue);
-
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProerty.getRules(), innerType, allDataTypes.left().value(), true);
+ ImmutablePair<String, Boolean> pair = propertyOperation
+ .validateAndUpdateRules(propertyType, groupInstanceProerty.getRules(), innerType, allDataTypes.left().value(), true);
if (pair.getRight() != null && !pair.getRight()) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProerty.getName(), propertyType);
+ BeEcompErrorManager.getInstance()
+ .logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProerty.getName(), propertyType);
return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT);
}
propertyOperation.updateRulesInPropertyValue(propertyValueData, groupInstanceProerty, groupInstanceId);
-
Either<PropertyValueData, JanusGraphOperationStatus> updateRes = janusGraphGenericDao
.updateNode(propertyValueData, PropertyValueData.class);
if (updateRes.isRight()) {
@@ -450,108 +430,56 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
return Either.left(updateRes.left().value());
}
}
-
}
- private static final class UpdateDataContainer<SomeData, SomeValueData> {
- final Wrapper<SomeValueData> valueDataWrapper;
- final Wrapper<SomeData> dataWrapper;
- final GraphEdgeLabels graphEdge;
- final Supplier<Class<SomeData>> someDataClassGen;
- final Supplier<Class<SomeValueData>> someValueDataClassGen;
- final NodeTypeEnum nodeType;
- final NodeTypeEnum nodeTypeValue;
-
- private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier<Class<SomeData>> someDataClassGen, Supplier<Class<SomeValueData>> someValueDataClassGen, NodeTypeEnum nodeType, NodeTypeEnum nodeTypeValue) {
- super();
- this.valueDataWrapper = new Wrapper<>();
- this.dataWrapper = new Wrapper<>();
- this.graphEdge = graphEdge;
- this.someDataClassGen = someDataClassGen;
- this.someValueDataClassGen = someValueDataClassGen;
- this.nodeType = nodeType;
- this.nodeTypeValue = nodeTypeValue;
- }
-
- public Wrapper<SomeValueData> getValueDataWrapper() {
- return valueDataWrapper;
- }
-
- public Wrapper<SomeData> getDataWrapper() {
- return dataWrapper;
- }
-
- public GraphEdgeLabels getGraphEdge() {
- return graphEdge;
- }
-
- public Supplier<Class<SomeData>> getSomeDataClassGen() {
- return someDataClassGen;
- }
-
- public Supplier<Class<SomeValueData>> getSomeValueDataClassGen() {
- return someValueDataClassGen;
- }
-
- public NodeTypeEnum getNodeType() {
- return nodeType;
- }
-
- public NodeTypeEnum getNodeTypeValue() {
- return nodeTypeValue;
- }
- }
-
- private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
- String resourceInstanceId, Wrapper<JanusGraphOperationStatus> errorWrapper) {
-
+ private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(
+ UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
+ String resourceInstanceId, Wrapper<JanusGraphOperationStatus> errorWrapper) {
if (errorWrapper.isEmpty()) {
// Verify VFC instance Exist
validateGIExist(resourceInstanceId, errorWrapper);
}
-
if (errorWrapper.isEmpty()) {
// Example: Verify Property connected to VFC exist
validateElementConnectedToComponentExist(updateDataContainer, resourceInstanceProerty, errorWrapper);
}
-
if (errorWrapper.isEmpty()) {
// Example: Verify PropertyValue connected to VFC Instance exist
validateElementConnectedToComponentInstanceExist(updateDataContainer, resourceInstanceProerty, errorWrapper);
}
-
if (errorWrapper.isEmpty()) {
// Example: Verify PropertyValue connected Property
validateElementConnectedToInstance(updateDataContainer, resourceInstanceProerty, errorWrapper);
}
}
- private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToInstance(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
- Wrapper<JanusGraphOperationStatus> errorWrapper) {
+ private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToInstance(
+ UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
+ Wrapper<JanusGraphOperationStatus> errorWrapper) {
Either<ImmutablePair<SomeData, GraphEdge>, JanusGraphOperationStatus> child = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(),
updateDataContainer.getGraphEdge(), updateDataContainer.getNodeType(), updateDataContainer.getSomeDataClassGen().get());
-
if (child.isRight()) {
JanusGraphOperationStatus status = child.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
status = JanusGraphOperationStatus.INVALID_ID;
}
errorWrapper.setInnerElement(status);
-
} else {
updateDataContainer.getDataWrapper().setInnerElement(child.left().value().left);
}
}
- private <SomeValueData extends GraphNode, SomeData extends GraphNode> void validateElementConnectedToComponentInstanceExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer,
- IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper<JanusGraphOperationStatus> errorWrapper) {
+ private <SomeValueData extends GraphNode, SomeData extends GraphNode> void validateElementConnectedToComponentInstanceExist(
+ UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
+ Wrapper<JanusGraphOperationStatus> errorWrapper) {
String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid();
if (valueUniqueUid == null) {
errorWrapper.setInnerElement(JanusGraphOperationStatus.INVALID_ID);
} else {
Either<SomeValueData, JanusGraphOperationStatus> findPropertyValueRes = janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid, updateDataContainer.getSomeValueDataClassGen().get());
+ .getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid,
+ updateDataContainer.getSomeValueDataClassGen().get());
if (findPropertyValueRes.isRight()) {
JanusGraphOperationStatus status = findPropertyValueRes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -564,12 +492,12 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
}
- private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToComponentExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer,
- IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper<JanusGraphOperationStatus> errorWrapper) {
+ private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToComponentExist(
+ UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceElementConnected,
+ Wrapper<JanusGraphOperationStatus> errorWrapper) {
String uniqueId = resourceInstanceElementConnected.getUniqueId();
Either<SomeData, JanusGraphOperationStatus> findPropertyDefRes = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get());
-
if (findPropertyDefRes.isRight()) {
JanusGraphOperationStatus status = findPropertyDefRes.right().value();
errorWrapper.setInnerElement(status);
@@ -580,12 +508,15 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
validateGIExist(resourceInstanceId, null, errorWrapper);
}
- private void validateGIExist(String resourceInstanceId, Wrapper<GroupInstanceData> compInsDataWrapper, Wrapper<JanusGraphOperationStatus> errorWrapper) {
+ private void validateGIExist(String resourceInstanceId, Wrapper<GroupInstanceData> compInsDataWrapper,
+ Wrapper<JanusGraphOperationStatus> errorWrapper) {
validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.GroupInstance, () -> GroupInstanceData.class, compInsDataWrapper, errorWrapper);
}
- public <ElementData extends GraphNode> void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType, Supplier<Class<ElementData>> elementClassGen, Wrapper<ElementData> elementDataWrapper,
- Wrapper<JanusGraphOperationStatus> errorWrapper) {
+ public <ElementData extends GraphNode> void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType,
+ Supplier<Class<ElementData>> elementClassGen,
+ Wrapper<ElementData> elementDataWrapper,
+ Wrapper<JanusGraphOperationStatus> errorWrapper) {
Either<ElementData, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(elementNodeType), elementUniqueId, elementClassGen.get());
if (findResInstanceRes.isRight()) {
@@ -601,8 +532,8 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
}
- private void buildGroupInstanceFromGroup(GroupInstance groupInstance, GroupDefinition groupDefinition, Map<String, PropertyValueData> groupInstancePropertyValues) {
-
+ private void buildGroupInstanceFromGroup(GroupInstance groupInstance, GroupDefinition groupDefinition,
+ Map<String, PropertyValueData> groupInstancePropertyValues) {
groupInstance.setGroupName(groupDefinition.getName());
groupInstance.setInvariantUUID(groupDefinition.getInvariantUUID());
groupInstance.setDescription(groupDefinition.getDescription());
@@ -611,17 +542,16 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
groupInstance.setArtifactsUuid(groupDefinition.getArtifactsUuid());
groupInstance.setType(groupDefinition.getType());
groupInstance.setGroupUUID(groupDefinition.getGroupUUID());
-
List<GroupInstanceProperty> groupInstanceProperties = groupDefinition.convertToGroupProperties()
- //converts List of GroupProperties to List of GroupInstanceProperties and updates it with group instance property data
- .stream().map(p -> getUpdatedConvertedProperty(p, groupInstancePropertyValues)).collect(Collectors.toList());
+ //converts List of GroupProperties to List of GroupInstanceProperties and updates it with group instance property data
+ .stream().map(p -> getUpdatedConvertedProperty(p, groupInstancePropertyValues)).collect(Collectors.toList());
groupInstance.convertFromGroupInstancesProperties(groupInstanceProperties);
}
- private GroupInstanceProperty getUpdatedConvertedProperty(GroupProperty groupProperty, Map<String, PropertyValueData> groupInstancePropertyValues){
-
+ private GroupInstanceProperty getUpdatedConvertedProperty(GroupProperty groupProperty,
+ Map<String, PropertyValueData> groupInstancePropertyValues) {
GroupInstanceProperty updatedProperty = new GroupInstanceProperty(groupProperty, groupProperty.getValue());
- if(!MapUtils.isEmpty(groupInstancePropertyValues) && groupInstancePropertyValues.containsKey(groupProperty.getName())){
+ if (!MapUtils.isEmpty(groupInstancePropertyValues) && groupInstancePropertyValues.containsKey(groupProperty.getName())) {
PropertyValueData groupInstancePropertyValue = groupInstancePropertyValues.get(groupProperty.getName());
updatedProperty.setValue(groupInstancePropertyValue.getValue());
updatedProperty.setValueUniqueUid(groupInstancePropertyValue.getUniqueId());
@@ -630,9 +560,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
private Either<List<ImmutablePair<String, String>>, JanusGraphOperationStatus> getGroupArtifactsPairs(String groupUniqueId) {
-
Either<List<ImmutablePair<String, String>>, JanusGraphOperationStatus> result = null;
-
Either<List<ImmutablePair<ArtifactData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF,
NodeTypeEnum.ArtifactRef, ArtifactData.class);
@@ -642,9 +570,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
status = JanusGraphOperationStatus.OK;
}
result = Either.right(status);
-
} else {
-
List<ImmutablePair<String, String>> artifactsList = new ArrayList<>();
List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenNodes.left().value();
if (list != null) {
@@ -656,48 +582,39 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
artifactsList.add(artifact);
}
}
-
- log.debug("The artifacts list related to group {} is {}",groupUniqueId,artifactsList);
+ log.debug("The artifacts list related to group {} is {}", groupUniqueId, artifactsList);
result = Either.left(artifactsList);
}
-
return result;
-
}
- public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
-
+ public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum,
+ String oldArtifactId, ArtifactData newArtifact) {
return this.dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact);
-
}
- private StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
-
+ private StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum,
+ String oldArtifactId, ArtifactData newArtifact) {
Either<List<GroupInstance>, StorageOperationStatus> allGroupsFromGraph = getAllGroupInstances(componentId, componentTypeEnum);
if (allGroupsFromGraph.isRight()) {
return allGroupsFromGraph.right().value();
}
-
List<GroupInstance> allGroups = allGroupsFromGraph.left().value();
if (allGroups == null || allGroups.isEmpty()) {
return StorageOperationStatus.OK;
}
-
// Find all groups which contains this artifact id
- List<GroupInstance> associatedGroups = allGroups.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(oldArtifactId)).collect(Collectors.toList());
-
+ List<GroupInstance> associatedGroups = allGroups.stream()
+ .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(oldArtifactId)).collect(Collectors.toList());
if (associatedGroups != null && !associatedGroups.isEmpty()) {
-
- log.debug("The groups {} contains the artifact {}",associatedGroups.stream().map(GroupInstanceDataDefinition::getName).collect(Collectors.toList()),oldArtifactId);
-
+ log.debug("The groups {} contains the artifact {}",
+ associatedGroups.stream().map(GroupInstanceDataDefinition::getName).collect(Collectors.toList()), oldArtifactId);
UniqueIdData oldArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, oldArtifactId);
UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifact.getArtifactDataDefinition().getUniqueId());
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel());
-
for (GroupInstance groupDefinition : associatedGroups) {
UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.GroupInstance, groupDefinition.getUniqueId());
-
Either<GraphRelation, JanusGraphOperationStatus> deleteRelation = janusGraphGenericDao
.deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF);
log.trace("After dissociate group {} from artifact {}", groupDefinition.getName(), oldArtifactId);
@@ -708,7 +625,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
-
Either<GraphRelation, JanusGraphOperationStatus> createRelation = janusGraphGenericDao
.createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props);
log.trace("After associate group {} to artifact {}", groupDefinition.getName(), newArtifact.getUniqueIdKey());
@@ -720,36 +636,87 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
}
-
}
return StorageOperationStatus.OK;
}
private Either<Map<String, PropertyValueData>, JanusGraphOperationStatus> getAllGroupInstancePropertyValuesData(GroupInstanceData groupInstData) {
-
Either<Map<String, PropertyValueData>, JanusGraphOperationStatus> result = null;
- try{
- Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, JanusGraphOperationStatus> getPropertyValueChildrenRes =
- janusGraphGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE,
- NodeTypeEnum.PropertyValue, PropertyValueData.class, true);
- if(getPropertyValueChildrenRes.isRight()){
+ try {
+ Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, JanusGraphOperationStatus> getPropertyValueChildrenRes = janusGraphGenericDao
+ .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE,
+ NodeTypeEnum.PropertyValue, PropertyValueData.class, true);
+ if (getPropertyValueChildrenRes.isRight()) {
JanusGraphOperationStatus status = getPropertyValueChildrenRes.right().value();
log.debug("Failed to fetch property value nodes for group instance {}. Status is {}. ", groupInstData.getName(), status);
- if(status == JanusGraphOperationStatus.NOT_FOUND){
+ if (status == JanusGraphOperationStatus.NOT_FOUND) {
result = Either.left(null);
- }else{
+ } else {
result = Either.right(status);
}
- }else{
- result = Either.left(getPropertyValueChildrenRes.left().value().stream()
- .collect(Collectors.toMap(pair->(String)(pair.getRight().getProperties().get(GraphPropertiesDictionary.PROPERTY_NAME.getProperty())), ImmutablePair::getLeft)));
+ } else {
+ result = Either.left(getPropertyValueChildrenRes.left().value().stream().collect(Collectors
+ .toMap(pair -> (String) (pair.getRight().getProperties().get(GraphPropertiesDictionary.PROPERTY_NAME.getProperty())),
+ ImmutablePair::getLeft)));
}
- } catch(Exception e){
- log.debug("The Exception occured during fetch group instance () property values. The message is {}. ", groupInstData.getName(), e.getMessage(), e);
- if(result == null){
+ } catch (Exception e) {
+ log.debug("The Exception occured during fetch group instance () property values. The message is {}. ", groupInstData.getName(),
+ e.getMessage(), e);
+ if (result == null) {
result = Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
}
}
return result;
}
+
+ private static final class UpdateDataContainer<SomeData, SomeValueData> {
+
+ final Wrapper<SomeValueData> valueDataWrapper;
+ final Wrapper<SomeData> dataWrapper;
+ final GraphEdgeLabels graphEdge;
+ final Supplier<Class<SomeData>> someDataClassGen;
+ final Supplier<Class<SomeValueData>> someValueDataClassGen;
+ final NodeTypeEnum nodeType;
+ final NodeTypeEnum nodeTypeValue;
+
+ private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier<Class<SomeData>> someDataClassGen,
+ Supplier<Class<SomeValueData>> someValueDataClassGen, NodeTypeEnum nodeType, NodeTypeEnum nodeTypeValue) {
+ super();
+ this.valueDataWrapper = new Wrapper<>();
+ this.dataWrapper = new Wrapper<>();
+ this.graphEdge = graphEdge;
+ this.someDataClassGen = someDataClassGen;
+ this.someValueDataClassGen = someValueDataClassGen;
+ this.nodeType = nodeType;
+ this.nodeTypeValue = nodeTypeValue;
+ }
+
+ public Wrapper<SomeValueData> getValueDataWrapper() {
+ return valueDataWrapper;
+ }
+
+ public Wrapper<SomeData> getDataWrapper() {
+ return dataWrapper;
+ }
+
+ public GraphEdgeLabels getGraphEdge() {
+ return graphEdge;
+ }
+
+ public Supplier<Class<SomeData>> getSomeDataClassGen() {
+ return someDataClassGen;
+ }
+
+ public Supplier<Class<SomeValueData>> getSomeValueDataClassGen() {
+ return someValueDataClassGen;
+ }
+
+ public NodeTypeEnum getNodeType() {
+ return nodeType;
+ }
+
+ public NodeTypeEnum getNodeTypeValue() {
+ return nodeTypeValue;
+ }
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java
index 164fa4d444..effdbebf4c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java
@@ -17,10 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.springframework.util.CollectionUtils.isEmpty;
+
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.function.Function;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
@@ -35,36 +44,38 @@ import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupProperty;
+import org.openecomp.sdc.be.model.GroupTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation;
import org.openecomp.sdc.be.model.operations.StorageException;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.resources.data.*;
+import org.openecomp.sdc.be.resources.data.ArtifactData;
+import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
+import org.openecomp.sdc.be.resources.data.GroupData;
+import org.openecomp.sdc.be.resources.data.GroupTypeData;
+import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
+import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Component;
-import java.util.*;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-import static org.springframework.util.CollectionUtils.isEmpty;
-
-
@Component
public class GroupOperation extends AbstractOperation implements IGroupOperation {
-
private static final Logger log = Logger.getLogger(GroupOperation.class.getName());
- private final JanusGraphDao janusGraphDao;
- private final TopologyTemplateOperation topologyTemplateOperation;
+ private final JanusGraphDao janusGraphDao;
+ private final TopologyTemplateOperation topologyTemplateOperation;
private final PropertyOperation propertyOperation;
private final GroupTypeOperation groupTypeOperation;
private final ApplicationDataTypeCache dataTypeCache;
- public GroupOperation(JanusGraphDao janusGraphDao, TopologyTemplateOperation topologyTemplateOperation, PropertyOperation propertyOperation, GroupTypeOperation groupTypeOperation, ApplicationDataTypeCache dataTypeCache) {
+ public GroupOperation(JanusGraphDao janusGraphDao, TopologyTemplateOperation topologyTemplateOperation, PropertyOperation propertyOperation,
+ GroupTypeOperation groupTypeOperation, ApplicationDataTypeCache dataTypeCache) {
this.janusGraphDao = janusGraphDao;
this.topologyTemplateOperation = topologyTemplateOperation;
this.propertyOperation = propertyOperation;
@@ -73,9 +84,8 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
private GroupDefinition convertGroupDataToGroupDefinition(GroupData groupData) {
- return new GroupDefinition(groupData.getGroupDataDefinition());
-
- }
+ return new GroupDefinition(groupData.getGroupDataDefinition());
+ }
/**
* get members of group
@@ -84,127 +94,96 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
* @return
*/
private Either<Map<String, String>, JanusGraphOperationStatus> getGroupMembers(String groupUniqueId) {
-
Either<Map<String, String>, JanusGraphOperationStatus> result = null;
-
Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_MEMBER,
NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
-
if (childrenNodes.isRight()) {
JanusGraphOperationStatus status = childrenNodes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
status = JanusGraphOperationStatus.OK;
}
result = Either.right(status);
-
} else {
-
Map<String, String> compInstaMap = new HashMap<>();
List<ImmutablePair<ComponentInstanceData, GraphEdge>> list = childrenNodes.left().value();
if (list != null) {
for (ImmutablePair<ComponentInstanceData, GraphEdge> pair : list) {
ComponentInstanceData componentInstanceData = pair.getKey();
-
String compInstUniqueId = componentInstanceData.getComponentInstDataDefinition().getUniqueId();
String compInstName = componentInstanceData.getName();
compInstaMap.put(compInstName, compInstUniqueId);
}
}
-
result = Either.left(compInstaMap);
}
-
return result;
}
private Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeOfGroup(String groupUniqueId) {
-
Either<ImmutablePair<GroupTypeData, GraphEdge>, StorageOperationStatus> groupTypeRes = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.GroupType,
- GroupTypeData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
-
+ GroupTypeData.class).right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (groupTypeRes.isRight()) {
StorageOperationStatus status = groupTypeRes.right().value();
log.debug("Cannot find group type associated with capability {}. Status is {}", groupUniqueId, status);
-
- BeEcompErrorManager.getInstance().logBeFailedFindAssociationError("Fetch Group type", NodeTypeEnum.GroupType.getName(), groupUniqueId, String.valueOf(status));
+ BeEcompErrorManager.getInstance()
+ .logBeFailedFindAssociationError("Fetch Group type", NodeTypeEnum.GroupType.getName(), groupUniqueId, String.valueOf(status));
return Either.right(groupTypeRes.right().value());
}
-
GroupTypeData groupTypeData = groupTypeRes.left().value().getKey();
-
return groupTypeOperation.getGroupTypeByUid(groupTypeData.getGroupTypeDataDefinition().getUniqueId());
-
}
/**
* get all properties of the group.
- *
+ * <p>
* the propert definition is taken from the group type.
*
* @param groupUid
* @return
*/
private Either<List<GroupProperty>, StorageOperationStatus> getGroupProperties(String groupUid) {
-
List<GroupProperty> groupPropertiesList = new ArrayList<>();
-
Either<GroupTypeDefinition, StorageOperationStatus> groupTypeOfGroupRes = getGroupTypeOfGroup(groupUid);
-
if (groupTypeOfGroupRes.isRight()) {
StorageOperationStatus status = groupTypeOfGroupRes.right().value();
return Either.right(status);
}
-
GroupTypeDefinition groupTypeDefinition = groupTypeOfGroupRes.left().value();
-
// Get the properties on the group type of this group
List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
-
if (isEmpty(groupTypeProperties)) {
return Either.right(StorageOperationStatus.OK);
}
-
- Map<String, PropertyDefinition> uidToPropDefMap = groupTypeProperties.stream().collect(Collectors.toMap(PropertyDefinition::getUniqueId, Function.identity()));
-
+ Map<String, PropertyDefinition> uidToPropDefMap = groupTypeProperties.stream()
+ .collect(Collectors.toMap(PropertyDefinition::getUniqueId, Function.identity()));
// Find all properties values on the group
Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, StorageOperationStatus> propertyImplNodes = janusGraphGenericDao
.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUid, GraphEdgeLabels.PROPERTY_VALUE,
- NodeTypeEnum.PropertyValue, PropertyValueData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
-
+ NodeTypeEnum.PropertyValue, PropertyValueData.class).right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (propertyImplNodes.isRight()) {
StorageOperationStatus status = propertyImplNodes.right().value();
if (status == StorageOperationStatus.NOT_FOUND) {
- groupPropertiesList = groupTypeProperties.stream().map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
+ groupPropertiesList = groupTypeProperties.stream().map(p -> new GroupProperty(p, p.getDefaultValue(), null))
+ .collect(Collectors.toList());
return Either.left(groupPropertiesList);
} else {
return Either.right(status);
}
}
-
List<ImmutablePair<PropertyValueData, GraphEdge>> list = propertyImplNodes.left().value();
if (isEmpty(list)) {
return Either.right(StorageOperationStatus.OK);
}
-
List<String> processedProps = new ArrayList<>();
-
for (ImmutablePair<PropertyValueData, GraphEdge> propertyValue : list) {
-
PropertyValueData propertyValueData = propertyValue.getLeft();
String propertyValueUid = propertyValueData.getUniqueId();
String value = propertyValueData.getValue();
-
Either<ImmutablePair<PropertyData, GraphEdge>, StorageOperationStatus> propertyDefRes = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL,
- NodeTypeEnum.Property, PropertyData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ NodeTypeEnum.Property, PropertyData.class).right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (propertyDefRes.isRight()) {
StorageOperationStatus status = propertyDefRes.right().value();
if (status == StorageOperationStatus.NOT_FOUND) {
@@ -212,63 +191,52 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
return Either.right(status);
}
-
ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value();
-
PropertyData propertyData = propertyDefPair.left;
String propertyUniqueId = propertyData.getPropertyDataDefinition().getUniqueId();
-
PropertyDefinition propertyDefinition = uidToPropDefMap.get(propertyUniqueId);
GroupProperty groupProperty = new GroupProperty(propertyDefinition, value, propertyValueUid);
-
processedProps.add(propertyUniqueId);
-
groupPropertiesList.add(groupProperty);
-
}
-
// Find all properties which does not have property value on the group.
List<GroupProperty> leftProps = groupTypeProperties.stream()
- // filter out the group type properties which already processed
- .filter(p -> !processedProps.contains(p.getUniqueId()))
- .map(p -> new GroupProperty(p, p.getDefaultValue(), null))
- .collect(Collectors.toList());
+ // filter out the group type properties which already processed
+ .filter(p -> !processedProps.contains(p.getUniqueId())).map(p -> new GroupProperty(p, p.getDefaultValue(), null))
+ .collect(Collectors.toList());
if (leftProps != null) {
groupPropertiesList.addAll(leftProps);
}
-
return Either.left(groupPropertiesList);
}
- public Either<List<GraphRelation>, StorageOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) {
-
+ public Either<List<GraphRelation>, StorageOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId,
+ NodeTypeEnum componentTypeEnum,
+ String artifactId) {
List<GraphRelation> relations = new ArrayList<>();
Either<List<GraphRelation>, StorageOperationStatus> result = Either.left(relations);
-
- Either<List<GroupDefinition>, StorageOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false);
+ Either<List<GroupDefinition>, StorageOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true,
+ false);
if (allGroupsFromGraph.isRight()) {
StorageOperationStatus status = allGroupsFromGraph.right().value();
return Either.right(status);
}
-
List<GroupDefinition> allGroups = allGroupsFromGraph.left().value();
if (isEmpty(allGroups)) {
return Either.right(StorageOperationStatus.OK);
}
-
// Find all groups which contains this artifact id
- List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(artifactId)).collect(Collectors.toList());
-
+ List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(artifactId))
+ .collect(Collectors.toList());
if (isNotEmpty(associatedGroups)) {
- log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(GroupDataDefinition::getName).collect(Collectors.toList()), artifactId);
-
+ log.debug("The groups {} contains the artifact {}",
+ associatedGroups.stream().map(GroupDataDefinition::getName).collect(Collectors.toList()), artifactId);
UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId);
for (GroupDefinition groupDefinition : associatedGroups) {
UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId());
Either<GraphRelation, StorageOperationStatus> deleteRelation = janusGraphGenericDao
- .deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (deleteRelation.isRight()) {
StorageOperationStatus status = deleteRelation.right().value();
if (status == StorageOperationStatus.NOT_FOUND) {
@@ -276,27 +244,21 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
return Either.right(status);
}
-
relations.add(deleteRelation.left().value());
}
-
return result;
-
} else {
log.debug("No group under component id {} is associated to artifact {}", componentId, artifactId);
return Either.right(StorageOperationStatus.OK);
}
-
}
- public Either<GroupDefinition, StorageOperationStatus> getGroupFromGraph(String uniqueId, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) {
-
+ public Either<GroupDefinition, StorageOperationStatus> getGroupFromGraph(String uniqueId, boolean skipProperties, boolean skipMembers,
+ boolean skipArtifacts) {
Either<GroupDefinition, StorageOperationStatus> result = null;
-
Either<GroupData, StorageOperationStatus> groupRes = janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), uniqueId, GroupData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), uniqueId, GroupData.class).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (groupRes.isRight()) {
StorageOperationStatus status = groupRes.right().value();
log.debug("Failed to retrieve group {} from graph. Status is {}", uniqueId, status);
@@ -304,29 +266,20 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
result = Either.right(status);
return result;
}
-
GroupData groupData = groupRes.left().value();
-
GroupDefinition groupDefinition = convertGroupDataToGroupDefinition(groupData);
-
Either<GroupTypeDefinition, StorageOperationStatus> groupTypeOfGroup = getGroupTypeOfGroup(uniqueId);
-
if (groupTypeOfGroup.isRight()) {
StorageOperationStatus status = groupTypeOfGroup.right().value();
log.debug("Failed to retrieve capability type of capability {}. Status is {}", uniqueId, status);
-
result = Either.right(status);
return result;
}
-
GroupTypeDefinition groupTypeDefinition = groupTypeOfGroup.left().value();
-
groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
-
if (!skipMembers) {
- Either<Map<String, String>, StorageOperationStatus> membersRes = getGroupMembers(uniqueId)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ Either<Map<String, String>, StorageOperationStatus> membersRes = getGroupMembers(uniqueId).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (membersRes.isRight()) {
StorageOperationStatus status = membersRes.right().value();
if (status != StorageOperationStatus.OK) {
@@ -338,7 +291,6 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
groupDefinition.setMembers(members);
}
}
-
if (!skipProperties) {
Either<List<GroupProperty>, StorageOperationStatus> propertiesRes = getGroupProperties(uniqueId);
if (propertiesRes.isRight()) {
@@ -352,11 +304,9 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
groupDefinition.convertFromGroupProperties(properties);
}
}
-
if (!skipArtifacts) {
- Either<List<ImmutablePair<String, String>>, StorageOperationStatus> artifactsRes = getGroupArtifactsPairs(uniqueId)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ Either<List<ImmutablePair<String, String>>, StorageOperationStatus> artifactsRes = getGroupArtifactsPairs(uniqueId).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (artifactsRes.isRight()) {
StorageOperationStatus status = artifactsRes.right().value();
if (status != StorageOperationStatus.OK) {
@@ -366,7 +316,6 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
} else {
List<String> artifactsUid = new ArrayList<>();
List<String> artifactsUUID = new ArrayList<>();
-
List<ImmutablePair<String, String>> list = artifactsRes.left().value();
if (list != null) {
for (ImmutablePair<String, String> pair : list) {
@@ -381,55 +330,40 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
}
result = Either.left(groupDefinition);
-
return result;
-
}
public boolean isGroupExist(String groupName, boolean inTransaction) {
-
Either<List<GroupData>, JanusGraphOperationStatus> eitherGroup = null;
try {
Map<String, Object> properties = new HashMap<>();
properties.put(GraphPropertiesDictionary.NAME.getProperty(), groupName);
-
- eitherGroup = janusGraphGenericDao
- .getByCriteria(NodeTypeEnum.Group, properties, GroupData.class);
+ eitherGroup = janusGraphGenericDao.getByCriteria(NodeTypeEnum.Group, properties, GroupData.class);
return eitherGroup.isLeft() && !eitherGroup.left().value().isEmpty();
-
} finally {
handleTransactionCommitRollback(inTransaction, eitherGroup);
}
}
- protected Either<List<GroupDefinition>, StorageOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) {
-
+ protected Either<List<GroupDefinition>, StorageOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum,
+ boolean skipProperties, boolean skipMembers,
+ boolean skipArtifacts) {
List<GroupDefinition> groups = new ArrayList<>();
-
Either<List<ImmutablePair<GroupData, GraphEdge>>, StorageOperationStatus> childrenNodes = janusGraphGenericDao
.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group,
- GroupData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
-
+ GroupData.class).right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (childrenNodes.isRight()) {
StorageOperationStatus status = childrenNodes.right().value();
return Either.right(status);
}
-
List<ImmutablePair<GroupData, GraphEdge>> graphGroups = childrenNodes.left().value();
-
if (isEmpty(graphGroups)) {
return Either.right(StorageOperationStatus.NOT_FOUND);
}
-
-
-
- for (ImmutablePair<GroupData, GraphEdge> pair : graphGroups) {
-
+ for (ImmutablePair<GroupData, GraphEdge> pair : graphGroups) {
String groupUniqueId = pair.left.getGroupDataDefinition().getUniqueId();
- Either<GroupDefinition, StorageOperationStatus> groupRes = this.getGroupFromGraph(groupUniqueId, skipProperties, skipMembers, skipArtifacts);
-
+ Either<GroupDefinition, StorageOperationStatus> groupRes = this
+ .getGroupFromGraph(groupUniqueId, skipProperties, skipMembers, skipArtifacts);
if (groupRes.isRight()) {
StorageOperationStatus status = groupRes.right().value();
if (status == StorageOperationStatus.NOT_FOUND) {
@@ -439,45 +373,37 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
} else {
groups.add(groupRes.left().value());
}
-
}
-
return Either.left(groups);
}
- private StorageOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
-
- Either<List<GroupDefinition>, StorageOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false);
- if (allGroupsFromGraph.isRight()) {
- return allGroupsFromGraph.right().value();
-
- }
-
+ private StorageOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum,
+ String oldArtifactId, ArtifactData newArtifact) {
+ Either<List<GroupDefinition>, StorageOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true,
+ false);
+ if (allGroupsFromGraph.isRight()) {
+ return allGroupsFromGraph.right().value();
+ }
List<GroupDefinition> allGroups = allGroupsFromGraph.left().value();
if (isEmpty(allGroups)) {
return StorageOperationStatus.OK;
}
-
// Find all groups which contains this artifact id
- List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(oldArtifactId)).collect(Collectors.toList());
-
+ List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(oldArtifactId))
+ .collect(Collectors.toList());
if (isNotEmpty(associatedGroups)) {
-
- log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(GroupDataDefinition::getName).collect(Collectors.toList()), oldArtifactId);
-
+ log.debug("The groups {} contains the artifact {}",
+ associatedGroups.stream().map(GroupDataDefinition::getName).collect(Collectors.toList()), oldArtifactId);
UniqueIdData oldArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, oldArtifactId);
UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifact.getArtifactDataDefinition().getUniqueId());
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel());
-
for (GroupDefinition groupDefinition : associatedGroups) {
UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId());
-
Either<GraphRelation, StorageOperationStatus> deleteRelation = janusGraphGenericDao
- .deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
- log.trace("After dissociate group {} from artifact {}" , groupDefinition.getName(), oldArtifactId);
+ .deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ log.trace("After dissociate group {} from artifact {}", groupDefinition.getName(), oldArtifactId);
if (deleteRelation.isRight()) {
StorageOperationStatus status = deleteRelation.right().value();
if (status == StorageOperationStatus.NOT_FOUND) {
@@ -485,12 +411,10 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
return status;
}
-
Either<GraphRelation, StorageOperationStatus> createRelation = janusGraphGenericDao
- .createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
- log.trace("After associate group {} to artifact {}" , groupDefinition.getName(), newArtifact.getUniqueIdKey());
+ .createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ log.trace("After associate group {} to artifact {}", groupDefinition.getName(), newArtifact.getUniqueIdKey());
if (createRelation.isRight()) {
StorageOperationStatus status = createRelation.right().value();
if (status == StorageOperationStatus.NOT_FOUND) {
@@ -499,25 +423,21 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return status;
}
}
-
}
return StorageOperationStatus.OK;
}
- public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction) {
-
+ public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId,
+ ArtifactData newArtifact, boolean inTransaction) {
StorageOperationStatus result = null;
-
try {
- StorageOperationStatus status = this.dissociateAndAssociateGroupsFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact);
-
+ StorageOperationStatus status = this
+ .dissociateAndAssociateGroupsFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
return status;
}
-
result = StorageOperationStatus.OK;
return result;
-
} finally {
if (!inTransaction) {
if (result == null || result != StorageOperationStatus.OK) {
@@ -533,9 +453,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
private Either<List<ImmutablePair<String, String>>, JanusGraphOperationStatus> getGroupArtifactsPairs(String groupUniqueId) {
-
Either<List<ImmutablePair<String, String>>, JanusGraphOperationStatus> result = null;
-
Either<List<ImmutablePair<ArtifactData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF,
NodeTypeEnum.ArtifactRef, ArtifactData.class);
@@ -545,9 +463,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
status = JanusGraphOperationStatus.OK;
}
result = Either.right(status);
-
} else {
-
List<ImmutablePair<String, String>> artifactsList = new ArrayList<>();
List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenNodes.left().value();
if (list != null) {
@@ -559,19 +475,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
artifactsList.add(artifact);
}
}
-
log.debug("The artifacts list related to group {} is {}", groupUniqueId, artifactsList);
result = Either.left(artifactsList);
}
-
return result;
-
}
public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property) {
-
StorageOperationStatus result = null;
- String innerType = property.getSchema() == null ? null : property.getSchema().getProperty() == null ? null : property.getSchema().getProperty().getType();
+ String innerType =
+ property.getSchema() == null ? null : property.getSchema().getProperty() == null ? null : property.getSchema().getProperty().getType();
Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
Either<Object, Boolean> isValid = null;
if (allDataTypes.isRight()) {
@@ -579,14 +492,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
log.debug("Failed to fetch data types from cache. Status is {}. ", status);
result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
- if(result == null){
- isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), property.getValue(), innerType, allDataTypes.left().value());
- if(isValid.isRight()){
+ if (result == null) {
+ isValid = propertyOperation
+ .validateAndUpdatePropertyValue(property.getType(), property.getValue(), innerType, allDataTypes.left().value());
+ if (isValid.isRight()) {
log.debug("Failed to validate property value {}. Status is {}. ", property.getValue(), StorageOperationStatus.INVALID_PROPERTY);
- result = StorageOperationStatus.INVALID_PROPERTY;
+ result = StorageOperationStatus.INVALID_PROPERTY;
}
}
- if(result == null){
+ if (result == null) {
String validValue = String.valueOf(isValid.left().value());
property.setValue(validValue);
result = StorageOperationStatus.OK;
@@ -594,33 +508,36 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return result;
}
- public StorageOperationStatus updateGroupProperties(org.openecomp.sdc.be.model.Component containerComponent, String groupId, List<PropertyDataDefinition> propertiesToUpdate) {
- log.debug("#updateGroupProperties - updating the properties of group {} in component {}", groupId, containerComponent.getUniqueId());
- Optional<GroupDefinition> group = containerComponent.getGroupById(groupId);
- if (group.isPresent()){
- return janusGraphDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.NoParse)
- .either(containerVertex -> updateGroupProperties(containerVertex, group.get(), propertiesToUpdate),
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
- } else {
- throw new StorageException(StorageOperationStatus.NOT_FOUND, groupId);
- }
- }
-
- private StorageOperationStatus updateGroupProperties(GraphVertex container, GroupDefinition group, List<PropertyDataDefinition> propertiesToUpdate) {
- List<PropertyDataDefinition> groupProperties = group.getProperties();
- List<PropertyDataDefinition> updatedGroupProperties = updateGroupProperties(groupProperties, propertiesToUpdate);
- group.setProperties(updatedGroupProperties);
- return topologyTemplateOperation.updateGroupOfToscaElement(container, group);
- }
+ public StorageOperationStatus updateGroupProperties(org.openecomp.sdc.be.model.Component containerComponent, String groupId,
+ List<PropertyDataDefinition> propertiesToUpdate) {
+ log.debug("#updateGroupProperties - updating the properties of group {} in component {}", groupId, containerComponent.getUniqueId());
+ Optional<GroupDefinition> group = containerComponent.getGroupById(groupId);
+ if (group.isPresent()) {
+ return janusGraphDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.NoParse)
+ .either(containerVertex -> updateGroupProperties(containerVertex, group.get(), propertiesToUpdate),
+ DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ } else {
+ throw new StorageException(StorageOperationStatus.NOT_FOUND, groupId);
+ }
+ }
- private List<PropertyDataDefinition> updateGroupProperties(List<PropertyDataDefinition> currentGroupProperties, List<PropertyDataDefinition> toBeUpdatedProperties) {
- Map<String, PropertyDataDefinition> currPropsByName = MapUtil.toMap(currentGroupProperties, PropertyDataDefinition::getName);
- overrideCurrentPropertiesWithUpdatedProperties(currPropsByName, toBeUpdatedProperties);
- return new ArrayList<>(currPropsByName.values());
- }
+ private StorageOperationStatus updateGroupProperties(GraphVertex container, GroupDefinition group,
+ List<PropertyDataDefinition> propertiesToUpdate) {
+ List<PropertyDataDefinition> groupProperties = group.getProperties();
+ List<PropertyDataDefinition> updatedGroupProperties = updateGroupProperties(groupProperties, propertiesToUpdate);
+ group.setProperties(updatedGroupProperties);
+ return topologyTemplateOperation.updateGroupOfToscaElement(container, group);
+ }
- private void overrideCurrentPropertiesWithUpdatedProperties(Map<String, PropertyDataDefinition> currPropsByName, List<PropertyDataDefinition> toBeUpdatedProperties) {
- toBeUpdatedProperties.forEach(prop -> currPropsByName.put(prop.getName(), prop));
- }
+ private List<PropertyDataDefinition> updateGroupProperties(List<PropertyDataDefinition> currentGroupProperties,
+ List<PropertyDataDefinition> toBeUpdatedProperties) {
+ Map<String, PropertyDataDefinition> currPropsByName = MapUtil.toMap(currentGroupProperties, PropertyDataDefinition::getName);
+ overrideCurrentPropertiesWithUpdatedProperties(currPropsByName, toBeUpdatedProperties);
+ return new ArrayList<>(currPropsByName.values());
+ }
+ private void overrideCurrentPropertiesWithUpdatedProperties(Map<String, PropertyDataDefinition> currPropsByName,
+ List<PropertyDataDefinition> toBeUpdatedProperties) {
+ toBeUpdatedProperties.forEach(prop -> currPropsByName.put(prop.getName(), prop));
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java
index ebaaf81cd8..c37ddaa449 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java
@@ -17,16 +17,26 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
+import static org.openecomp.sdc.be.dao.janusgraph.JanusGraphUtils.buildNotInPredicate;
+
import com.google.common.base.Strings;
-import org.janusgraph.graphdb.query.JanusGraphPredicate;
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.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;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.janusgraph.graphdb.query.JanusGraphPredicate;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
@@ -46,22 +56,19 @@ 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.api.TypeOperations;
import org.openecomp.sdc.be.model.utils.TypeCompareUtils;
-import org.openecomp.sdc.be.resources.data.*;
+import org.openecomp.sdc.be.resources.data.CapabilityData;
+import org.openecomp.sdc.be.resources.data.CapabilityTypeData;
+import org.openecomp.sdc.be.resources.data.GroupTypeData;
+import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Component;
-import java.util.*;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.dao.janusgraph.JanusGraphUtils.buildNotInPredicate;
-
@Component("group-type-operation")
public class GroupTypeOperation implements IGroupTypeOperation {
private static final Logger log = Logger.getLogger(GroupTypeOperation.class.getName());
private static final String CREATE_FLOW_CONTEXT = "CreateGroupType";
-
private final PropertyOperation propertyOperation;
private final JanusGraphGenericDao janusGraphGenericDao;
private final CapabilityTypeOperation capabilityTypeOperation;
@@ -69,11 +76,8 @@ public class GroupTypeOperation implements IGroupTypeOperation {
private final DerivedFromOperation derivedFromOperation;
private final OperationUtils operationUtils;
-
- public GroupTypeOperation(JanusGraphGenericDao janusGraphGenericDao,
- PropertyOperation propertyOperation,
- CapabilityTypeOperation capabilityTypeOperation,
- CapabilityOperation capabilityOperation,
+ public GroupTypeOperation(JanusGraphGenericDao janusGraphGenericDao, PropertyOperation propertyOperation,
+ CapabilityTypeOperation capabilityTypeOperation, CapabilityOperation capabilityOperation,
DerivedFromOperation derivedFromOperation, OperationUtils operationUtils) {
this.janusGraphGenericDao = janusGraphGenericDao;
this.propertyOperation = propertyOperation;
@@ -86,56 +90,48 @@ public class GroupTypeOperation implements IGroupTypeOperation {
public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition) {
Either<GroupTypeDefinition, StorageOperationStatus> validationRes = validateUpdateProperties(groupTypeDefinition);
if (validationRes.isRight()) {
- log.error("#addGroupType - One or all properties of group type {} not valid. status is {}", groupTypeDefinition, validationRes.right().value());
+ log.error("#addGroupType - One or all properties of group type {} not valid. status is {}", groupTypeDefinition,
+ validationRes.right().value());
return validationRes;
}
-
return addGroupType(groupTypeDefinition, true);
}
public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition, boolean inTransaction) {
-
Either<GroupTypeDefinition, StorageOperationStatus> result = null;
-
try {
-
Either<GroupTypeData, JanusGraphOperationStatus> eitherStatus = addGroupTypeToGraph(groupTypeDefinition);
-
if (eitherStatus.isRight()) {
- BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name());
+ BeEcompErrorManager.getInstance()
+ .logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
- }
- else {
+ } else {
result = getGroupType(eitherStatus.left().value().getUniqueId(), inTransaction);
}
-
return result;
-
} finally {
janusGraphGenericDao.handleTransactionCommitRollback(inTransaction, result);
}
-
}
- public Either<GroupTypeDefinition, StorageOperationStatus> updateGroupType(GroupTypeDefinition updatedGroupType, GroupTypeDefinition currGroupType) {
+ public Either<GroupTypeDefinition, StorageOperationStatus> updateGroupType(GroupTypeDefinition updatedGroupType,
+ GroupTypeDefinition currGroupType) {
log.debug("updating group type {}", updatedGroupType.getType());
return updateGroupTypeOnGraph(updatedGroupType, currGroupType);
}
-
-
+
public Either<GroupTypeDefinition, StorageOperationStatus> validateUpdateProperties(GroupTypeDefinition groupTypeDefinition) {
JanusGraphOperationStatus error = null;
if (CollectionUtils.isNotEmpty(groupTypeDefinition.getProperties()) && !Strings.isNullOrEmpty(groupTypeDefinition.getDerivedFrom())) {
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> allPropertiesRes =
- getAllGroupTypePropertiesFromAllDerivedFrom(groupTypeDefinition.getDerivedFrom());
- if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals(
- JanusGraphOperationStatus.NOT_FOUND)) {
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> allPropertiesRes = getAllGroupTypePropertiesFromAllDerivedFrom(
+ groupTypeDefinition.getDerivedFrom());
+ if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
error = allPropertiesRes.right().value();
log.debug("Couldn't fetch derived from property nodes for group type {}, error: {}", groupTypeDefinition.getType(), error);
}
if (error == null && !allPropertiesRes.left().value().isEmpty()) {
- Either<List<PropertyDefinition>, JanusGraphOperationStatus> validatePropertiesRes = propertyOperation.validatePropertiesUniqueness(allPropertiesRes.left().value(),
- groupTypeDefinition.getProperties());
+ Either<List<PropertyDefinition>, JanusGraphOperationStatus> validatePropertiesRes = propertyOperation
+ .validatePropertiesUniqueness(allPropertiesRes.left().value(), groupTypeDefinition.getProperties());
if (validatePropertiesRes.isRight()) {
error = validatePropertiesRes.right().value();
}
@@ -146,15 +142,13 @@ public class GroupTypeOperation implements IGroupTypeOperation {
}
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
-
+
private Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getAllGroupTypePropertiesFromAllDerivedFrom(String firstParentType) {
- return janusGraphGenericDao
- .getNode(GraphPropertiesDictionary.TYPE.getProperty(), firstParentType, GroupTypeData.class)
- .left()
- .bind(parentGroup -> propertyOperation.getAllTypePropertiesFromAllDerivedFrom(parentGroup.getUniqueId(), NodeTypeEnum.GroupType, GroupTypeData.class));
+ return janusGraphGenericDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), firstParentType, GroupTypeData.class).left().bind(
+ parentGroup -> propertyOperation
+ .getAllTypePropertiesFromAllDerivedFrom(parentGroup.getUniqueId(), NodeTypeEnum.GroupType, GroupTypeData.class));
}
-
private StorageOperationStatus mergeCapabilities(GroupTypeDefinition groupTypeDef) {
Map<String, CapabilityDefinition> updatedGroupTypeCapabilities = groupTypeDef.getCapabilities();
Map<String, CapabilityDefinition> newGroupTypeCapabilities;
@@ -163,27 +157,22 @@ public class GroupTypeOperation implements IGroupTypeOperation {
StorageOperationStatus status = oldCapabilitiesRes.right().value();
if (status == StorageOperationStatus.NOT_FOUND) {
newGroupTypeCapabilities = updatedGroupTypeCapabilities;
- }
- else {
+ } else {
return status;
}
- }
- else {
+ } else {
Map<String, CapabilityDefinition> oldCapabilities = asCapabilitiesMap(oldCapabilitiesRes.left().value());
newGroupTypeCapabilities = collectNewCapabilities(updatedGroupTypeCapabilities, oldCapabilities);
-
- for(Map.Entry<String, CapabilityDefinition> oldEntry: oldCapabilities.entrySet()) {
+ for (Map.Entry<String, CapabilityDefinition> oldEntry : oldCapabilities.entrySet()) {
String key = oldEntry.getKey();
- CapabilityDefinition newCapDef = updatedGroupTypeCapabilities != null? updatedGroupTypeCapabilities.get(key): null;
+ CapabilityDefinition newCapDef = updatedGroupTypeCapabilities != null ? updatedGroupTypeCapabilities.get(key) : null;
CapabilityDefinition oldCapDef = oldEntry.getValue();
-
StorageOperationStatus deleteCapResult = deleteOutdatedCapability(newGroupTypeCapabilities, newCapDef, oldCapDef);
- if(deleteCapResult != StorageOperationStatus.OK) {
+ if (deleteCapResult != StorageOperationStatus.OK) {
return deleteCapResult;
}
}
}
-
JanusGraphOperationStatus createCapResult = createCapabilities(new GroupTypeData(groupTypeDef), newGroupTypeCapabilities);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createCapResult);
}
@@ -192,24 +181,21 @@ public class GroupTypeOperation implements IGroupTypeOperation {
* @param newGroupTypeCapabilities
* @param newCapDef
* @param oldCapDef
- * @return
+ * @return
*/
- private StorageOperationStatus deleteOutdatedCapability(Map<String, CapabilityDefinition> newGroupTypeCapabilities, CapabilityDefinition newCapDef, CapabilityDefinition oldCapDef) {
- if(!isUpdateAllowed(newCapDef, oldCapDef)) {
+ private StorageOperationStatus deleteOutdatedCapability(Map<String, CapabilityDefinition> newGroupTypeCapabilities,
+ CapabilityDefinition newCapDef, CapabilityDefinition oldCapDef) {
+ if (!isUpdateAllowed(newCapDef, oldCapDef)) {
return StorageOperationStatus.MATCH_NOT_FOUND;
}
-
if (!TypeCompareUtils.capabilityEquals(oldCapDef, newCapDef)) {
StorageOperationStatus deleteCapResult = capabilityOperation.deleteCapability(oldCapDef);
-
- if(deleteCapResult == StorageOperationStatus.OK) {
+ if (deleteCapResult == StorageOperationStatus.OK) {
newGroupTypeCapabilities.put(newCapDef.getName(), newCapDef);
- }
- else {
+ } else {
return deleteCapResult;
}
}
-
return StorageOperationStatus.OK;
}
@@ -218,12 +204,10 @@ public class GroupTypeOperation implements IGroupTypeOperation {
log.error("#upsertCapabilities - Failed due to attempt to delete the capability with id {}", oldCapDef.getUniqueId());
return false;
}
-
if (newCapDef.getType() == null || !newCapDef.getType().equals(oldCapDef.getType())) {
log.error("#upsertCapabilities - Failed due to attempt to change type of the capability with id {}", oldCapDef.getUniqueId());
return false;
}
-
return true;
}
@@ -232,48 +216,39 @@ public class GroupTypeOperation implements IGroupTypeOperation {
* @param oldCapabilities
* @return
*/
- private Map<String, CapabilityDefinition> collectNewCapabilities(
- Map<String, CapabilityDefinition> updatedGroupTypeCapabilities,
- Map<String, CapabilityDefinition> oldCapabilities) {
+ private Map<String, CapabilityDefinition> collectNewCapabilities(Map<String, CapabilityDefinition> updatedGroupTypeCapabilities,
+ Map<String, CapabilityDefinition> oldCapabilities) {
return updatedGroupTypeCapabilities != null ? updatedGroupTypeCapabilities.entrySet().stream()
- .filter(entry -> !oldCapabilities.containsKey(entry.getKey()))
- .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) : new HashMap<>();
+ .filter(entry -> !oldCapabilities.containsKey(entry.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
+ : new HashMap<>();
}
private JanusGraphOperationStatus createCapabilities(GroupTypeData groupTypeData, Map<String, CapabilityDefinition> groupCapabilities) {
if (MapUtils.isEmpty(groupCapabilities)) {
return JanusGraphOperationStatus.OK;
}
-
- return groupCapabilities.values().stream()
- .map(v -> createCapability(groupTypeData, v))
- .filter(Either::isRight)
- .findFirst()
- .map(either -> either.right().value())
- .orElse(JanusGraphOperationStatus.OK);
+ return groupCapabilities.values().stream().map(v -> createCapability(groupTypeData, v)).filter(Either::isRight).findFirst()
+ .map(either -> either.right().value()).orElse(JanusGraphOperationStatus.OK);
}
- private Either<GraphRelation, JanusGraphOperationStatus> createCapability(GroupTypeData groupTypeData, CapabilityDefinition capabilityDef) {
- Either<CapabilityTypeDefinition, JanusGraphOperationStatus> eitherCapData = capabilityTypeOperation.getCapabilityTypeByType(capabilityDef.getType());
- return eitherCapData
- .left()
- .map(CapabilityTypeData::new)
- .left()
- .bind(capTypeData -> capabilityOperation.addCapabilityToGraph(groupTypeData.getUniqueId(), capTypeData, capabilityDef))
- .left()
- .bind(capData -> connectToCapability(groupTypeData, capData, capabilityDef.getName()));
+ private Either<GraphRelation, JanusGraphOperationStatus> createCapability(GroupTypeData groupTypeData, CapabilityDefinition capabilityDef) {
+ Either<CapabilityTypeDefinition, JanusGraphOperationStatus> eitherCapData = capabilityTypeOperation
+ .getCapabilityTypeByType(capabilityDef.getType());
+ return eitherCapData.left().map(CapabilityTypeData::new).left()
+ .bind(capTypeData -> capabilityOperation.addCapabilityToGraph(groupTypeData.getUniqueId(), capTypeData, capabilityDef)).left()
+ .bind(capData -> connectToCapability(groupTypeData, capData, capabilityDef.getName()));
}
-
/**
* Get capability with all relevant properties
+ *
* @param groupTypeId
* @return
*/
private Either<List<CapabilityDefinition>, StorageOperationStatus> getCapablities(String groupTypeId) {
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, JanusGraphOperationStatus> groupCapabilitiesOnGraph =
- janusGraphGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), groupTypeId, GraphEdgeLabels.GROUP_TYPE_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class, true);
-
+ Either<List<ImmutablePair<CapabilityData, GraphEdge>>, JanusGraphOperationStatus> groupCapabilitiesOnGraph = janusGraphGenericDao
+ .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), groupTypeId, GraphEdgeLabels.GROUP_TYPE_CAPABILITY,
+ NodeTypeEnum.Capability, CapabilityData.class, true);
if (groupCapabilitiesOnGraph.isRight()) {
JanusGraphOperationStatus capabilityStatus = groupCapabilitiesOnGraph.right().value();
if (capabilityStatus == JanusGraphOperationStatus.NOT_FOUND) {
@@ -281,60 +256,46 @@ public class GroupTypeOperation implements IGroupTypeOperation {
}
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(capabilityStatus));
}
-
List<ImmutablePair<CapabilityData, GraphEdge>> groupCapabilites = groupCapabilitiesOnGraph.left().value();
groupCapabilites.forEach(this::fillCapabilityName);
-
- return capabilityOperation.getCapabilitiesWithProps(groupCapabilites)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ return capabilityOperation.getCapabilitiesWithProps(groupCapabilites).right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
private void fillCapabilityName(ImmutablePair<CapabilityData, GraphEdge> pair) {
- pair.getLeft().getCapabilityDataDefinition().setName((String)pair.getRight().getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty()));
+ pair.getLeft().getCapabilityDataDefinition()
+ .setName((String) pair.getRight().getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty()));
}
- private Either<GraphRelation, JanusGraphOperationStatus> connectToCapability(GroupTypeData groupTypeData, CapabilityData capabilityData, String capabilityName) {
+ private Either<GraphRelation, JanusGraphOperationStatus> connectToCapability(GroupTypeData groupTypeData, CapabilityData capabilityData,
+ String capabilityName) {
Map<String, Object> properties = new HashMap<>();
properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName);
-
return janusGraphGenericDao.createRelation(groupTypeData, capabilityData, GraphEdgeLabels.GROUP_TYPE_CAPABILITY, properties);
}
-
public List<GroupTypeDefinition> getAllGroupTypes(Set<String> excludedGroupTypes) {
- Map<String, Map.Entry<JanusGraphPredicate, Object>> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(), excludedGroupTypes);
+ Map<String, Map.Entry<JanusGraphPredicate, Object>> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(),
+ excludedGroupTypes);
List<GroupTypeData> groupTypes = janusGraphGenericDao
- .getByCriteriaWithPredicate(NodeTypeEnum.GroupType, predicateCriteria, GroupTypeData.class)
- .left()
- .on(operationUtils::onJanusGraphOperationFailure);
+ .getByCriteriaWithPredicate(NodeTypeEnum.GroupType, predicateCriteria, GroupTypeData.class).left()
+ .on(operationUtils::onJanusGraphOperationFailure);
return convertGroupTypesToDefinition(groupTypes);
}
-
private List<GroupTypeDefinition> convertGroupTypesToDefinition(List<GroupTypeData> groupTypes) {
- return groupTypes.stream()
- .map(type -> new GroupTypeDefinition(type.getGroupTypeDataDefinition()))
- .collect(Collectors.toList());
+ return groupTypes.stream().map(type -> new GroupTypeDefinition(type.getGroupTypeDataDefinition())).collect(Collectors.toList());
}
-
public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByUid(String uniqueId) {
log.debug("#getGroupTypeByUid - fetching group type with id {}", uniqueId);
- return janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), uniqueId, GroupTypeData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
- .left()
- .bind(groupType -> buildGroupTypeDefinition(uniqueId, groupType));
+ return janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), uniqueId, GroupTypeData.class).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus).left().bind(groupType -> buildGroupTypeDefinition(uniqueId, groupType));
}
public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId, boolean inTransaction) {
Either<GroupTypeDefinition, StorageOperationStatus> result = null;
try {
-
Either<GroupTypeDefinition, StorageOperationStatus> ctResult = getGroupTypeByUid(uniqueId);
-
if (ctResult.isRight()) {
StorageOperationStatus status = ctResult.right().value();
if (status != StorageOperationStatus.NOT_FOUND) {
@@ -343,14 +304,11 @@ public class GroupTypeOperation implements IGroupTypeOperation {
result = Either.right(ctResult.right().value());
return result;
}
-
result = Either.left(ctResult.left().value());
-
return result;
} finally {
janusGraphGenericDao.handleTransactionCommitRollback(inTransaction, result);
}
-
}
public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String type) {
@@ -361,12 +319,11 @@ public class GroupTypeOperation implements IGroupTypeOperation {
Map<String, Object> mapCriteria = new HashMap<>();
mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type);
mapCriteria.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
-
return getGroupTypeByCriteria(type, mapCriteria, inTransaction);
-
}
- public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByCriteria(String type, Map<String, Object> properties, boolean inTransaction) {
+ public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByCriteria(String type, Map<String, Object> properties,
+ boolean inTransaction) {
Either<GroupTypeDefinition, StorageOperationStatus> result = null;
try {
if (type == null || type.isEmpty()) {
@@ -374,23 +331,17 @@ public class GroupTypeOperation implements IGroupTypeOperation {
result = Either.right(StorageOperationStatus.INVALID_ID);
return result;
}
-
Either<List<GroupTypeData>, StorageOperationStatus> groupTypeEither = janusGraphGenericDao
- .getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (groupTypeEither.isRight()) {
result = Either.right(groupTypeEither.right().value());
} else {
- GroupTypeDataDefinition dataDefinition = groupTypeEither.left().value().stream()
- .map(GroupTypeData::getGroupTypeDataDefinition)
- .findFirst()
- .get();
+ GroupTypeDataDefinition dataDefinition = groupTypeEither.left().value().stream().map(GroupTypeData::getGroupTypeDataDefinition)
+ .findFirst().get();
result = getGroupTypeByUid(dataDefinition.getUniqueId());
-
}
return result;
-
} finally {
janusGraphGenericDao.handleTransactionCommitRollback(inTransaction, result);
}
@@ -398,39 +349,28 @@ public class GroupTypeOperation implements IGroupTypeOperation {
private Either<GroupTypeDefinition, StorageOperationStatus> buildGroupTypeDefinition(String uniqueId, GroupTypeData groupTypeNode) {
GroupTypeDefinition groupType = new GroupTypeDefinition(groupTypeNode.getGroupTypeDataDefinition());
- return fillDerivedFrom(uniqueId, groupType)
- .left()
- .map(derivedFrom -> fillProperties(uniqueId, groupType, derivedFrom))
- .left()
- .bind(props -> fillCapabilities(uniqueId, groupType));
+ return fillDerivedFrom(uniqueId, groupType).left().map(derivedFrom -> fillProperties(uniqueId, groupType, derivedFrom)).left()
+ .bind(props -> fillCapabilities(uniqueId, groupType));
}
-
+
private Either<GroupTypeDefinition, StorageOperationStatus> fillCapabilities(String uniqueId, GroupTypeDefinition groupType) {
- return getCapablities(uniqueId)
- .left()
- .map(capabilities -> {
- groupType.setCapabilities(asCapabilitiesMap(capabilities));
- return groupType;
- });
+ return getCapablities(uniqueId).left().map(capabilities -> {
+ groupType.setCapabilities(asCapabilitiesMap(capabilities));
+ return groupType;
+ });
}
private Either<GroupTypeData, StorageOperationStatus> fillDerivedFrom(String uniqueId, GroupTypeDefinition groupType) {
log.debug("#fillDerivedFrom - fetching group type {} derived node", groupType.getType());
- return derivedFromOperation.getDerivedFromChild(uniqueId, NodeTypeEnum.GroupType, GroupTypeData.class)
- .right()
- .bind(this::handleDerivedFromNotExist)
- .left()
- .map(derivedFrom -> setDerivedFrom(groupType, derivedFrom));
-
+ return derivedFromOperation.getDerivedFromChild(uniqueId, NodeTypeEnum.GroupType, GroupTypeData.class).right()
+ .bind(this::handleDerivedFromNotExist).left().map(derivedFrom -> setDerivedFrom(groupType, derivedFrom));
}
- private Either<List<PropertyDefinition>, StorageOperationStatus> fillProperties(String uniqueId, GroupTypeDefinition groupType, GroupTypeData derivedFromNode) {
+ private Either<List<PropertyDefinition>, StorageOperationStatus> fillProperties(String uniqueId, GroupTypeDefinition groupType,
+ GroupTypeData derivedFromNode) {
log.debug("#fillProperties - fetching all properties for group type {}", groupType.getType());
- return propertyOperation.findPropertiesOfNode(NodeTypeEnum.GroupType, uniqueId)
- .right()
- .bind(this::handleGroupTypeHasNoProperties)
- .left()
- .bind(propsMap -> fillDerivedFromProperties(groupType, derivedFromNode, new ArrayList<>(propsMap.values())));
+ return propertyOperation.findPropertiesOfNode(NodeTypeEnum.GroupType, uniqueId).right().bind(this::handleGroupTypeHasNoProperties).left()
+ .bind(propsMap -> fillDerivedFromProperties(groupType, derivedFromNode, new ArrayList<>(propsMap.values())));
}
Either<Map<String, PropertyDefinition>, StorageOperationStatus> handleGroupTypeHasNoProperties(JanusGraphOperationStatus err) {
@@ -440,17 +380,22 @@ public class GroupTypeOperation implements IGroupTypeOperation {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(err));
}
- private Either<List<PropertyDefinition>, StorageOperationStatus> fillDerivedFromProperties(GroupTypeDefinition groupType, GroupTypeData derivedFromNode, List<PropertyDefinition> groupTypeDirectProperties) {
+ private Either<List<PropertyDefinition>, StorageOperationStatus> fillDerivedFromProperties(GroupTypeDefinition groupType,
+ GroupTypeData derivedFromNode,
+ List<PropertyDefinition> groupTypeDirectProperties) {
if (derivedFromNode == null) {
groupType.setProperties(groupTypeDirectProperties);
return Either.left(groupTypeDirectProperties);
}
log.debug("#fillDerivedFromProperties - fetching all properties of derived from chain for group type {}", groupType.getType());
- return propertyOperation.getAllPropertiesRec(derivedFromNode.getUniqueId(), NodeTypeEnum.GroupType, GroupTypeData.class)
- .left()
- .map(derivedFromProps -> {groupTypeDirectProperties.addAll(derivedFromProps); return groupTypeDirectProperties;})
- .left()
- .map(allProps -> {groupType.setProperties(allProps);return allProps;});
+ return propertyOperation.getAllPropertiesRec(derivedFromNode.getUniqueId(), NodeTypeEnum.GroupType, GroupTypeData.class).left()
+ .map(derivedFromProps -> {
+ groupTypeDirectProperties.addAll(derivedFromProps);
+ return groupTypeDirectProperties;
+ }).left().map(allProps -> {
+ groupType.setProperties(allProps);
+ return allProps;
+ });
}
private Either<GroupTypeData, StorageOperationStatus> handleDerivedFromNotExist(StorageOperationStatus err) {
@@ -467,7 +412,6 @@ public class GroupTypeOperation implements IGroupTypeOperation {
return derivedFrom;
}
-
public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String type, String version) {
return getGroupTypeByTypeAndVersion(type, version, false);
}
@@ -476,7 +420,6 @@ public class GroupTypeOperation implements IGroupTypeOperation {
Map<String, Object> mapCriteria = new HashMap<>();
mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type);
mapCriteria.put(GraphPropertiesDictionary.VERSION.getProperty(), version);
-
return getGroupTypeByCriteria(type, mapCriteria, inTransaction);
}
@@ -493,33 +436,25 @@ public class GroupTypeOperation implements IGroupTypeOperation {
* @return
*/
private Either<GroupTypeData, JanusGraphOperationStatus> addGroupTypeToGraph(GroupTypeDefinition groupTypeDefinition) {
-
log.debug("Got group type {}", groupTypeDefinition);
-
String ctUniqueId = UniqueIdBuilder.buildGroupTypeUid(groupTypeDefinition.getType(), groupTypeDefinition.getVersion(), "grouptype");
-
GroupTypeData groupTypeData = buildGroupTypeData(groupTypeDefinition, ctUniqueId);
-
log.debug("Before adding group type to graph. groupTypeData = {}", groupTypeData);
-
- Either<GroupTypeData, JanusGraphOperationStatus> createGTResult = janusGraphGenericDao
- .createNode(groupTypeData, GroupTypeData.class);
+ Either<GroupTypeData, JanusGraphOperationStatus> createGTResult = janusGraphGenericDao.createNode(groupTypeData, GroupTypeData.class);
log.debug("After adding group type to graph. status is = {}", createGTResult);
-
if (createGTResult.isRight()) {
JanusGraphOperationStatus operationStatus = createGTResult.right().value();
log.error("Failed to add group type {} to graph. status is {}", groupTypeDefinition.getType(), operationStatus);
return Either.right(operationStatus);
}
-
GroupTypeData resultCTD = createGTResult.left().value();
List<PropertyDefinition> properties = groupTypeDefinition.getProperties();
- Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.GroupType, properties);
+ Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToCapablityType = propertyOperation
+ .addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.GroupType, properties);
if (addPropertiesToCapablityType.isRight()) {
log.error("Failed add properties {} to capability {}", properties, groupTypeDefinition.getType());
return Either.right(addPropertiesToCapablityType.right().value());
}
-
String derivedFrom = groupTypeDefinition.getDerivedFrom();
if (derivedFrom != null) {
Either<GraphRelation, JanusGraphOperationStatus> createRelation = connectToDerivedFrom(ctUniqueId, derivedFrom);
@@ -527,7 +462,6 @@ public class GroupTypeOperation implements IGroupTypeOperation {
return Either.right(createRelation.right().value());
}
}
-
Map<String, CapabilityDefinition> groupCapTypes = groupTypeDefinition.getCapabilities();
if (!MapUtils.isEmpty(groupCapTypes)) {
JanusGraphOperationStatus status = createCapabilities(groupTypeData, groupCapTypes);
@@ -535,23 +469,16 @@ public class GroupTypeOperation implements IGroupTypeOperation {
return Either.right(status);
}
}
-
return Either.left(createGTResult.left().value());
-
}
-
private Either<GraphRelation, JanusGraphOperationStatus> connectToDerivedFrom(String ctUniqueId, String derivedFrom) {
log.debug("Before creating relation between Group Type with id {} to its parent {}", ctUniqueId, derivedFrom);
-
- Either<GroupTypeData, JanusGraphOperationStatus> derivedFromGroupTypeResult =
- janusGraphGenericDao
- .getNode(GraphPropertiesDictionary.TYPE.getProperty(), derivedFrom, GroupTypeData.class);
-
+ Either<GroupTypeData, JanusGraphOperationStatus> derivedFromGroupTypeResult = janusGraphGenericDao
+ .getNode(GraphPropertiesDictionary.TYPE.getProperty(), derivedFrom, GroupTypeData.class);
if (derivedFromGroupTypeResult.isLeft()) {
UniqueIdData from = new UniqueIdData(NodeTypeEnum.GroupType, ctUniqueId);
GroupTypeData to = derivedFromGroupTypeResult.left().value();
-
Either<GraphRelation, JanusGraphOperationStatus> createRelation = janusGraphGenericDao
.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null);
log.debug("After create relation between Group Type with id {} to its parent {}, status is {}.", ctUniqueId, derivedFrom, createRelation);
@@ -564,9 +491,7 @@ public class GroupTypeOperation implements IGroupTypeOperation {
}
private GroupTypeData buildGroupTypeData(GroupTypeDefinition groupTypeDefinition, String ctUniqueId) {
-
GroupTypeData groupTypeData = new GroupTypeData(groupTypeDefinition);
-
groupTypeData.getGroupTypeDataDefinition().setUniqueId(ctUniqueId);
Long creationDate = groupTypeData.getGroupTypeDataDefinition().getCreationTime();
if (creationDate == null) {
@@ -574,7 +499,6 @@ public class GroupTypeOperation implements IGroupTypeOperation {
}
groupTypeData.getGroupTypeDataDefinition().setCreationTime(creationDate);
groupTypeData.getGroupTypeDataDefinition().setModificationTime(creationDate);
-
return groupTypeData;
}
@@ -585,10 +509,8 @@ public class GroupTypeOperation implements IGroupTypeOperation {
.getByCriteria(NodeTypeEnum.CapabilityType, propertiesToMatch, CapabilityTypeData.class);
if (getResponse.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = getResponse.right().value();
- log.debug("Couldn't fetch capability type {}, error: {}", childCandidateType,
- janusGraphOperationStatus);
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- janusGraphOperationStatus));
+ log.debug("Couldn't fetch capability type {}, error: {}", childCandidateType, janusGraphOperationStatus);
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
}
String childUniqueId = getResponse.left().value().get(0).getUniqueId();
Set<String> travelledTypes = new HashSet<>();
@@ -600,10 +522,8 @@ public class GroupTypeOperation implements IGroupTypeOperation {
if (childrenNodes.isRight()) {
if (childrenNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
JanusGraphOperationStatus janusGraphOperationStatus = getResponse.right().value();
- log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType,
- janusGraphOperationStatus);
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- janusGraphOperationStatus));
+ log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType, janusGraphOperationStatus);
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
} else {
log.debug("Derived from node is not found for type {} - this is OK for root capability.", childCandidateType);
return Either.left(false);
@@ -617,68 +537,57 @@ public class GroupTypeOperation implements IGroupTypeOperation {
childUniqueId = derivedFromUniqueId;
} while (!travelledTypes.contains(childUniqueId));
// this stop condition should never be used, if we use it, we have an
+
// illegal cycle in graph - "derived from" hierarchy cannot be cycled.
+
// It's here just to avoid infinite loop in case we have such cycle.
log.error("Detected a cycle of \"derived from\" edges starting at capability type node {}", childUniqueId);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
-
+
/**
* @param list
* @return
*/
private Map<String, CapabilityDefinition> asCapabilitiesMap(List<CapabilityDefinition> list) {
- return list.stream()
- .collect(Collectors.toMap(CapabilityDefinition::getName, Function.identity()));
+ return list.stream().collect(Collectors.toMap(CapabilityDefinition::getName, Function.identity()));
}
-
- private Either<GroupTypeDefinition, StorageOperationStatus> updateGroupTypeOnGraph(GroupTypeDefinition updatedGroupType, GroupTypeDefinition currGroupType) {
+ private Either<GroupTypeDefinition, StorageOperationStatus> updateGroupTypeOnGraph(GroupTypeDefinition updatedGroupType,
+ GroupTypeDefinition currGroupType) {
updateGroupTypeData(updatedGroupType, currGroupType);
- return janusGraphGenericDao.updateNode(new GroupTypeData(updatedGroupType), GroupTypeData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
- .left()
- .bind(updatedNode -> updateGroupProperties(updatedGroupType.getUniqueId(), updatedGroupType.getProperties()))
- .left()
- .bind(updatedProperties -> updateGroupDerivedFrom(updatedGroupType, currGroupType.getDerivedFrom()))
- .right()
- .bind(result -> TypeOperations.mapOkStatus(result, null))
- .left()
- .bind(updatedDerivedFrom -> TypeOperations.mapOkStatus(mergeCapabilities(updatedGroupType), updatedGroupType))
- .left()
- .bind(def -> getGroupTypeByUid(def.getUniqueId()));
- }
-
+ return janusGraphGenericDao.updateNode(new GroupTypeData(updatedGroupType), GroupTypeData.class).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus).left()
+ .bind(updatedNode -> updateGroupProperties(updatedGroupType.getUniqueId(), updatedGroupType.getProperties())).left()
+ .bind(updatedProperties -> updateGroupDerivedFrom(updatedGroupType, currGroupType.getDerivedFrom())).right()
+ .bind(result -> TypeOperations.mapOkStatus(result, null)).left()
+ .bind(updatedDerivedFrom -> TypeOperations.mapOkStatus(mergeCapabilities(updatedGroupType), updatedGroupType)).left()
+ .bind(def -> getGroupTypeByUid(def.getUniqueId()));
+ }
private Either<Map<String, PropertyData>, StorageOperationStatus> updateGroupProperties(String groupId, List<PropertyDefinition> properties) {
log.debug("#updateGroupProperties - updating group type properties for group type with id {}", groupId);
- Map<String, PropertyDefinition> mapProperties = properties != null? properties.stream()
- .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())): null;
- return propertyOperation.mergePropertiesAssociatedToNode(NodeTypeEnum.GroupType, groupId, mapProperties)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ Map<String, PropertyDefinition> mapProperties =
+ properties != null ? properties.stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())) : null;
+ return propertyOperation.mergePropertiesAssociatedToNode(NodeTypeEnum.GroupType, groupId, mapProperties).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
-
-
- private Either<GraphRelation, StorageOperationStatus> updateGroupDerivedFrom(GroupTypeDefinition updatedGroupType, String currDerivedFromGroupType) {
-
+ private Either<GraphRelation, StorageOperationStatus> updateGroupDerivedFrom(GroupTypeDefinition updatedGroupType,
+ String currDerivedFromGroupType) {
String groupTypeId = updatedGroupType.getUniqueId();
if (StringUtils.equals(updatedGroupType.getDerivedFrom(), currDerivedFromGroupType)) {
- return Strings.isNullOrEmpty(currDerivedFromGroupType)?
- Either.right(StorageOperationStatus.OK):
- getLatestGroupTypeByType(currDerivedFromGroupType, true)
- .left()
- .map(def -> null);
+ return Strings.isNullOrEmpty(currDerivedFromGroupType) ? Either.right(StorageOperationStatus.OK)
+ : getLatestGroupTypeByType(currDerivedFromGroupType, true).left().map(def -> null);
}
-
- StorageOperationStatus status = isLegalToReplaceParent(currDerivedFromGroupType, updatedGroupType.getDerivedFrom(), updatedGroupType.getType());
- if ( status != StorageOperationStatus.OK) {
+ StorageOperationStatus status = isLegalToReplaceParent(currDerivedFromGroupType, updatedGroupType.getDerivedFrom(),
+ updatedGroupType.getType());
+ if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
-
- log.debug("#updateGroupDerivedFrom - updating group derived from relation for group type with id {}. old derived type {}. new derived type {}", groupTypeId, currDerivedFromGroupType, updatedGroupType.getDerivedFrom());
+ log.debug(
+ "#updateGroupDerivedFrom - updating group derived from relation for group type with id {}. old derived type {}. new derived type {}",
+ groupTypeId, currDerivedFromGroupType, updatedGroupType.getDerivedFrom());
StorageOperationStatus deleteDerivedRelationStatus = deleteDerivedFromGroupType(groupTypeId, currDerivedFromGroupType);
if (deleteDerivedRelationStatus != StorageOperationStatus.OK) {
return Either.right(deleteDerivedRelationStatus);
@@ -687,28 +596,30 @@ public class GroupTypeOperation implements IGroupTypeOperation {
}
private StorageOperationStatus isLegalToReplaceParent(String oldTypeParent, String newTypeParent, String childType) {
- return derivedFromOperation.isUpdateParentAllowed(oldTypeParent, newTypeParent, childType, NodeTypeEnum.GroupType, GroupTypeData.class, t -> t.getGroupTypeDataDefinition().getType());
+ return derivedFromOperation.isUpdateParentAllowed(oldTypeParent, newTypeParent, childType, NodeTypeEnum.GroupType, GroupTypeData.class,
+ t -> t.getGroupTypeDataDefinition().getType());
}
-
+
private Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(GroupTypeDataDefinition groupTypeDef, String gtUniqueId) {
String derivedFrom = groupTypeDef.getDerivedFrom();
if (derivedFrom == null) {
return Either.left(null);
}
- log.debug("#addDerivedFromRelationBefore - adding derived from relation between group type {} to its parent {}", groupTypeDef.getType(), derivedFrom);
- return this.getLatestGroupTypeByType(derivedFrom, true)
- .left()
- .bind(derivedFromGroup -> derivedFromOperation.addDerivedFromRelation(gtUniqueId, derivedFromGroup.getUniqueId(), NodeTypeEnum.GroupType));
+ log.debug("#addDerivedFromRelationBefore - adding derived from relation between group type {} to its parent {}", groupTypeDef.getType(),
+ derivedFrom);
+ return this.getLatestGroupTypeByType(derivedFrom, true).left().bind(
+ derivedFromGroup -> derivedFromOperation.addDerivedFromRelation(gtUniqueId, derivedFromGroup.getUniqueId(), NodeTypeEnum.GroupType));
}
private StorageOperationStatus deleteDerivedFromGroupType(String groupTypeId, String derivedFromType) {
if (derivedFromType == null) {
return StorageOperationStatus.OK;
}
- log.debug("#deleteDerivedFromGroupType - deleting derivedFrom relation for group type with id {} and its derived type {}", groupTypeId, derivedFromType);
- return getLatestGroupTypeByType(derivedFromType, true)
- .either(derivedFromNode -> derivedFromOperation.removeDerivedFromRelation(groupTypeId, derivedFromNode.getUniqueId(), NodeTypeEnum.GroupType),
- err -> err);
+ log.debug("#deleteDerivedFromGroupType - deleting derivedFrom relation for group type with id {} and its derived type {}", groupTypeId,
+ derivedFromType);
+ return getLatestGroupTypeByType(derivedFromType, true).either(
+ derivedFromNode -> derivedFromOperation.removeDerivedFromRelation(groupTypeId, derivedFromNode.getUniqueId(), NodeTypeEnum.GroupType),
+ err -> err);
}
private void updateGroupTypeData(GroupTypeDefinition updatedTypeDefinition, GroupTypeDefinition currTypeDefinition) {
@@ -716,5 +627,4 @@ public class GroupTypeOperation implements IGroupTypeOperation {
updatedTypeDefinition.setCreationTime(currTypeDefinition.getCreationTime());
updatedTypeDefinition.setModificationTime(System.currentTimeMillis());
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java
index 823c33a311..88383e5bae 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
@@ -42,18 +45,11 @@ import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Component;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
@Component("heat-parameter-operation")
public class HeatParametersOperation implements IHeatParametersOperation {
public static final String EMPTY_VALUE = null;
-
private static final Logger log = Logger.getLogger(HeatParametersOperation.class.getName());
-
@javax.annotation.Resource
private JanusGraphGenericDao janusGraphGenericDao;
@@ -66,11 +62,9 @@ public class HeatParametersOperation implements IHeatParametersOperation {
}
public StorageOperationStatus getHeatParametersOfNode(NodeTypeEnum nodeType, String uniqueId, List<HeatParameterDefinition> properties) {
-
Either<List<ImmutablePair<HeatParameterData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.HEAT_PARAMETER, NodeTypeEnum.HeatParameter,
HeatParameterData.class);
-
if (childrenNodes.isRight()) {
JanusGraphOperationStatus status = childrenNodes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -78,36 +72,30 @@ public class HeatParametersOperation implements IHeatParametersOperation {
}
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
-
List<ImmutablePair<HeatParameterData, GraphEdge>> values = childrenNodes.left().value();
if (values != null) {
-
for (ImmutablePair<HeatParameterData, GraphEdge> immutablePair : values) {
GraphEdge edge = immutablePair.getValue();
String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
- if (log.isDebugEnabled())
+ if (log.isDebugEnabled()) {
log.debug("Property {} is associated to node {}", propertyName, uniqueId);
+ }
HeatParameterData propertyData = immutablePair.getKey();
HeatParameterDefinition propertyDefinition = convertParameterDataToParameterDefinition(propertyData, propertyName, uniqueId);
-
properties.add(propertyDefinition);
-
if (log.isTraceEnabled()) {
log.trace("getHeatParametersOfNode - property {} associated to node {}", propertyDefinition, uniqueId);
}
}
-
}
-
return StorageOperationStatus.OK;
}
- public StorageOperationStatus getParametersValueNodes(NodeTypeEnum parentNodeType, String parentUniqueId, List<HeatParameterValueData> heatValues) {
-
+ public StorageOperationStatus getParametersValueNodes(NodeTypeEnum parentNodeType, String parentUniqueId,
+ List<HeatParameterValueData> heatValues) {
Either<List<ImmutablePair<HeatParameterValueData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentUniqueId, GraphEdgeLabels.PARAMETER_VALUE,
NodeTypeEnum.HeatParameterValue, HeatParameterValueData.class);
-
if (childrenNodes.isRight()) {
JanusGraphOperationStatus status = childrenNodes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -115,36 +103,28 @@ public class HeatParametersOperation implements IHeatParametersOperation {
}
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
-
List<ImmutablePair<HeatParameterValueData, GraphEdge>> values = childrenNodes.left().value();
if (values != null) {
-
for (ImmutablePair<HeatParameterValueData, GraphEdge> immutablePair : values) {
GraphEdge edge = immutablePair.getValue();
String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
- log.trace("Heat value {} is associated to node {}", propertyName,parentUniqueId);
+ log.trace("Heat value {} is associated to node {}", propertyName, parentUniqueId);
HeatParameterValueData propertyData = immutablePair.getKey();
-
heatValues.add(propertyData);
}
-
}
-
return StorageOperationStatus.OK;
}
@Override
- public Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteAllHeatParametersAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) {
-
+ public Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteAllHeatParametersAssociatedToNode(NodeTypeEnum nodeType,
+ String uniqueId) {
List<HeatParameterDefinition> heatParams = new ArrayList<>();
StorageOperationStatus propertiesOfNodeRes = getHeatParametersOfNode(nodeType, uniqueId, heatParams);
-
if (!propertiesOfNodeRes.equals(StorageOperationStatus.OK) && !propertiesOfNodeRes.equals(StorageOperationStatus.NOT_FOUND)) {
return Either.right(propertiesOfNodeRes);
}
-
for (HeatParameterDefinition propertyDefinition : heatParams) {
-
String propertyUid = propertyDefinition.getUniqueId();
Either<HeatParameterData, JanusGraphOperationStatus> deletePropertyRes = deleteHeatParameterFromGraph(propertyUid);
if (deletePropertyRes.isRight()) {
@@ -155,25 +135,19 @@ public class HeatParametersOperation implements IHeatParametersOperation {
}
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
-
}
-
log.debug("The heat parameters deleted from node {} are {}", uniqueId, heatParams);
return Either.left(heatParams);
}
@Override
public StorageOperationStatus deleteAllHeatValuesAssociatedToNode(NodeTypeEnum parentNodeType, String parentUniqueId) {
-
List<HeatParameterValueData> heatValues = new ArrayList<>();
StorageOperationStatus propertiesOfNodeRes = getParametersValueNodes(parentNodeType, parentUniqueId, heatValues);
-
if (!propertiesOfNodeRes.equals(StorageOperationStatus.OK) && !propertiesOfNodeRes.equals(StorageOperationStatus.NOT_FOUND)) {
return propertiesOfNodeRes;
}
-
for (HeatParameterValueData propertyDefinition : heatValues) {
-
String propertyUid = (String) propertyDefinition.getUniqueId();
Either<HeatParameterValueData, JanusGraphOperationStatus> deletePropertyRes = deleteHeatParameterValueFromGraph(propertyUid);
if (deletePropertyRes.isRight()) {
@@ -184,52 +158,43 @@ public class HeatParametersOperation implements IHeatParametersOperation {
}
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
-
}
-
- log.debug("The heat values deleted from node {} are {}" , parentUniqueId, heatValues);
+ log.debug("The heat values deleted from node {} are {}", parentUniqueId, heatValues);
return StorageOperationStatus.OK;
}
private Either<HeatParameterData, JanusGraphOperationStatus> deleteHeatParameterFromGraph(String propertyId) {
- log.debug("Before deleting heat parameter from graph {}" , propertyId);
- return janusGraphGenericDao
- .deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameter), propertyId, HeatParameterData.class);
+ log.debug("Before deleting heat parameter from graph {}", propertyId);
+ return janusGraphGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameter), propertyId, HeatParameterData.class);
}
private Either<HeatParameterValueData, JanusGraphOperationStatus> deleteHeatParameterValueFromGraph(String propertyId) {
- log.debug("Before deleting heat parameter from graph {}" , propertyId);
- return janusGraphGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameterValue), propertyId, HeatParameterValueData.class);
+ log.debug("Before deleting heat parameter from graph {}", propertyId);
+ return janusGraphGenericDao
+ .deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameterValue), propertyId, HeatParameterValueData.class);
}
@Override
public StorageOperationStatus addPropertiesToGraph(List<HeatParameterDefinition> properties, String parentId, NodeTypeEnum nodeType) {
-
if (properties != null) {
for (HeatParameterDefinition propertyDefinition : properties) {
-
String propertyName = propertyDefinition.getName();
-
- Either<HeatParameterData, JanusGraphOperationStatus> addPropertyToGraph = addPropertyToGraph(propertyName, propertyDefinition, parentId, nodeType);
-
+ Either<HeatParameterData, JanusGraphOperationStatus> addPropertyToGraph = addPropertyToGraph(propertyName, propertyDefinition,
+ parentId, nodeType);
if (addPropertyToGraph.isRight()) {
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertyToGraph.right().value());
}
}
}
-
return StorageOperationStatus.OK;
-
}
@Override
public StorageOperationStatus updateHeatParameters(List<HeatParameterDefinition> properties) {
-
if (properties == null) {
return StorageOperationStatus.OK;
}
for (HeatParameterDefinition property : properties) {
-
HeatParameterData heatParameterData = new HeatParameterData(property);
Either<HeatParameterData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao
.updateNode(heatParameterData, HeatParameterData.class);
@@ -238,57 +203,46 @@ public class HeatParametersOperation implements IHeatParametersOperation {
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateNode.right().value());
}
}
-
return StorageOperationStatus.OK;
}
- public Either<HeatParameterData, JanusGraphOperationStatus> addPropertyToGraph(String propertyName, HeatParameterDefinition propertyDefinition, String parentId, NodeTypeEnum nodeType) {
-
+ public Either<HeatParameterData, JanusGraphOperationStatus> addPropertyToGraph(String propertyName, HeatParameterDefinition propertyDefinition,
+ String parentId, NodeTypeEnum nodeType) {
UniqueIdData parentNode = new UniqueIdData(nodeType, parentId);
-
propertyDefinition.setUniqueId(UniqueIdBuilder.buildHeatParameterUniqueId(parentId, propertyName));
HeatParameterData propertyData = new HeatParameterData(propertyDefinition);
-
- log.debug("Before adding property to graph {}" , propertyData);
+ log.debug("Before adding property to graph {}", propertyData);
Either<HeatParameterData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
.createNode(propertyData, HeatParameterData.class);
- log.debug("After adding property to graph {}" , propertyData);
+ log.debug("After adding property to graph {}", propertyData);
if (createNodeResult.isRight()) {
JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
return Either.right(operationStatus);
}
-
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
.createRelation(parentNode, propertyData, GraphEdgeLabels.HEAT_PARAMETER, props);
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate {} {} to heat parameter {} in graph. status is {}", nodeType.getName(), parentId, propertyName, operationStatus);
+ log.error("Failed to associate {} {} to heat parameter {} in graph. status is {}", nodeType.getName(), parentId, propertyName,
+ operationStatus);
return Either.right(operationStatus);
}
-
return Either.left(createNodeResult.left().value());
-
}
public StorageOperationStatus validateAndUpdateProperty(HeatParameterDefinition propertyDefinition) {
-
- log.trace("Going to validate property type and value. {}" , propertyDefinition);
-
+ log.trace("Going to validate property type and value. {}", propertyDefinition);
String propertyType = propertyDefinition.getType();
HeatParameterType type = getType(propertyType);
-
if (type == null) {
log.info("The type {} of heat parameter is invalid", type);
-
return StorageOperationStatus.INVALID_TYPE;
}
propertyDefinition.setType(type.getType());
-
log.trace("After validating property type {}", propertyType);
-
// validate default value
String defaultValue = propertyDefinition.getDefaultValue();
boolean isValidProperty = isValidValue(type, defaultValue);
@@ -296,18 +250,14 @@ public class HeatParametersOperation implements IHeatParametersOperation {
log.info("The value {} of property from type {} is invalid", defaultValue, type);
return StorageOperationStatus.INVALID_VALUE;
}
-
PropertyValueConverter converter = type.getConverter();
-
if (isEmptyValue(defaultValue)) {
- log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName() , EMPTY_VALUE);
-
+ log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
propertyDefinition.setDefaultValue(EMPTY_VALUE);
} else if (!isEmptyValue(defaultValue)) {
String convertedValue = converter.convert(defaultValue, null, null);
propertyDefinition.setDefaultValue(convertedValue);
}
-
// validate current value
String value = propertyDefinition.getCurrentValue();
isValidProperty = isValidValue(type, value);
@@ -315,49 +265,39 @@ public class HeatParametersOperation implements IHeatParametersOperation {
log.info("The value {} of property from type {} is invalid", value, type);
return StorageOperationStatus.INVALID_VALUE;
}
-
if (isEmptyValue(value)) {
log.debug("Value was not sent for property {}. Set value to {}", propertyDefinition.getName(), EMPTY_VALUE);
-
propertyDefinition.setCurrentValue(EMPTY_VALUE);
} else if (!value.equals("")) {
String convertedValue = converter.convert(value, null, null);
propertyDefinition.setCurrentValue(convertedValue);
}
-
return StorageOperationStatus.OK;
}
- public HeatParameterDefinition convertParameterDataToParameterDefinition(HeatParameterData propertyDataResult, String propertyName, String resourceId) {
+ public HeatParameterDefinition convertParameterDataToParameterDefinition(HeatParameterData propertyDataResult, String propertyName,
+ String resourceId) {
log.debug("convert to HeatParamereDefinition {}", propertyDataResult);
-
HeatParameterDefinition propertyDefResult = new HeatParameterDefinition(propertyDataResult.getHeatDataDefinition());
-
propertyDefResult.setName(propertyName);
-
return propertyDefResult;
}
private HeatParameterType getType(String propertyType) {
-
return HeatParameterType.isValidType(propertyType);
-
}
protected boolean isValidValue(HeatParameterType type, String value) {
if (isEmptyValue(value)) {
return true;
}
-
PropertyTypeValidator validator = type.getValidator();
-
boolean isValid = validator.isValid(value, null, null);
if (isValid) {
return true;
} else {
return false;
}
-
}
public boolean isEmptyValue(String value) {
@@ -375,13 +315,16 @@ public class HeatParametersOperation implements IHeatParametersOperation {
}
@Override
- public Either<HeatParameterValueData, StorageOperationStatus> updateHeatParameterValue(HeatParameterDefinition heatParam, String artifactId, String resourceInstanceId, String artifactLabel) {
+ public Either<HeatParameterValueData, StorageOperationStatus> updateHeatParameterValue(HeatParameterDefinition heatParam, String artifactId,
+ String resourceInstanceId, String artifactLabel) {
String heatEnvId = UniqueIdBuilder.buildHeatParameterValueUniqueId(resourceInstanceId, artifactLabel, heatParam.getName());
Either<HeatParameterValueData, JanusGraphOperationStatus> getNode = janusGraphGenericDao
.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId, HeatParameterValueData.class);
if (getNode.isRight() || getNode.left().value() == null) {
- if (heatParam.getCurrentValue() == null || (heatParam.getDefaultValue() != null && heatParam.getCurrentValue().equals(heatParam.getDefaultValue()))) {
- log.debug("Updated heat parameter value equals default value. No need to create heat parameter value for heat parameter {}", heatParam.getUniqueId());
+ if (heatParam.getCurrentValue() == null || (heatParam.getDefaultValue() != null && heatParam.getCurrentValue()
+ .equals(heatParam.getDefaultValue()))) {
+ log.debug("Updated heat parameter value equals default value. No need to create heat parameter value for heat parameter {}",
+ heatParam.getUniqueId());
return Either.left(null);
}
return createHeatParameterValue(heatParam, artifactId, resourceInstanceId, artifactLabel);
@@ -394,7 +337,8 @@ public class HeatParametersOperation implements IHeatParametersOperation {
public Either<HeatParameterValueData, StorageOperationStatus> updateHeatParameterValue(HeatParameterDefinition heatParam) {
HeatParameterValueData heatParameterValue = new HeatParameterValueData();
heatParameterValue.setUniqueId(heatParam.getUniqueId());
- if (heatParam.getCurrentValue() == null || (heatParam.getDefaultValue() != null && heatParam.getCurrentValue().equals(heatParam.getDefaultValue()))) {
+ if (heatParam.getCurrentValue() == null || (heatParam.getDefaultValue() != null && heatParam.getCurrentValue()
+ .equals(heatParam.getDefaultValue()))) {
Either<GraphRelation, JanusGraphOperationStatus> deleteParameterValueIncomingRelation = janusGraphGenericDao
.deleteIncomingRelationByCriteria(heatParameterValue, GraphEdgeLabels.PARAMETER_VALUE, null);
if (deleteParameterValueIncomingRelation.isRight()) {
@@ -402,7 +346,8 @@ public class HeatParametersOperation implements IHeatParametersOperation {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteParameterValueIncomingRelation.right().value()));
}
Either<Edge, JanusGraphOperationStatus> getOutgoingRelation = janusGraphGenericDao
- .getOutgoingEdgeByCriteria(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) heatParameterValue.getUniqueId(), GraphEdgeLabels.PARAMETER_IMPL, null);
+ .getOutgoingEdgeByCriteria(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) heatParameterValue.getUniqueId(),
+ GraphEdgeLabels.PARAMETER_IMPL, null);
if (getOutgoingRelation.isRight()) {
log.debug("Failed to get heat parameter value outgoing relation from graph. id = {}", heatParameterValue.getUniqueId());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getOutgoingRelation.right().value()));
@@ -413,7 +358,6 @@ public class HeatParametersOperation implements IHeatParametersOperation {
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
edge.remove();
-
Either<HeatParameterValueData, JanusGraphOperationStatus> deleteNode = janusGraphGenericDao
.deleteNode(heatParameterValue, HeatParameterValueData.class);
if (deleteNode.isRight()) {
@@ -432,9 +376,10 @@ public class HeatParametersOperation implements IHeatParametersOperation {
return Either.left(updateNode.left().value());
}
- public Either<HeatParameterValueData, StorageOperationStatus> createHeatParameterValue(HeatParameterDefinition heatParam, String artifactId, String resourceInstanceId, String artifactLabel) {
-
- Either<HeatParameterValueData, JanusGraphOperationStatus> addHeatValueToGraph = addHeatValueToGraph(heatParam, artifactLabel, artifactId, resourceInstanceId);
+ public Either<HeatParameterValueData, StorageOperationStatus> createHeatParameterValue(HeatParameterDefinition heatParam, String artifactId,
+ String resourceInstanceId, String artifactLabel) {
+ Either<HeatParameterValueData, JanusGraphOperationStatus> addHeatValueToGraph = addHeatValueToGraph(heatParam, artifactLabel, artifactId,
+ resourceInstanceId);
if (addHeatValueToGraph.isRight()) {
log.debug("Failed to create heat parameters value on graph for artifact {}", artifactId);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addHeatValueToGraph.right().value()));
@@ -442,13 +387,12 @@ public class HeatParametersOperation implements IHeatParametersOperation {
return Either.left(addHeatValueToGraph.left().value());
}
- public Either<HeatParameterValueData, JanusGraphOperationStatus> addHeatValueToGraph(HeatParameterDefinition heatParameter, String artifactLabel, String artifactId, String resourceInstanceId) {
-
+ public Either<HeatParameterValueData, JanusGraphOperationStatus> addHeatValueToGraph(HeatParameterDefinition heatParameter, String artifactLabel,
+ String artifactId, String resourceInstanceId) {
UniqueIdData heatEnvNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId);
HeatParameterValueData heatValueData = new HeatParameterValueData();
heatValueData.setUniqueId(UniqueIdBuilder.buildHeatParameterValueUniqueId(resourceInstanceId, artifactLabel, heatParameter.getName()));
heatValueData.setValue(heatParameter.getCurrentValue());
-
log.debug("Before adding property to graph {}", heatValueData);
Either<HeatParameterValueData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
.createNode(heatValueData, HeatParameterValueData.class);
@@ -458,14 +402,14 @@ public class HeatParametersOperation implements IHeatParametersOperation {
log.error("Failed to add heat value {} to graph. status is {}", heatValueData.getUniqueId(), operationStatus);
return Either.right(operationStatus);
}
-
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), heatParameter.getName());
Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
.createRelation(heatEnvNode, heatValueData, GraphEdgeLabels.PARAMETER_VALUE, props);
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate heat value {} to heat env artifact {} in graph. status is {}", heatValueData.getUniqueId(), artifactId, operationStatus);
+ log.error("Failed to associate heat value {} to heat env artifact {} in graph. status is {}", heatValueData.getUniqueId(), artifactId,
+ operationStatus);
return Either.right(operationStatus);
}
UniqueIdData heatParameterNode = new UniqueIdData(NodeTypeEnum.HeatParameter, heatParameter.getUniqueId());
@@ -473,12 +417,10 @@ public class HeatParametersOperation implements IHeatParametersOperation {
.createRelation(heatValueData, heatParameterNode, GraphEdgeLabels.PARAMETER_IMPL, null);
if (createRel2Result.isRight()) {
JanusGraphOperationStatus operationStatus = createRel2Result.right().value();
- log.error("Failed to associate heat value {} to heat parameter {} in graph. status is {}", heatValueData.getUniqueId(), heatParameter.getName(), operationStatus);
+ log.error("Failed to associate heat value {} to heat parameter {} in graph. status is {}", heatValueData.getUniqueId(),
+ heatParameter.getName(), operationStatus);
return Either.right(operationStatus);
}
-
return Either.left(createNodeResult.left().value());
-
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java
index b9a4c7f66f..c604fcc5b8 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -33,14 +34,15 @@ import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.operations.api.IInputsOperation;
-import org.openecomp.sdc.be.resources.data.*;
+import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
+import org.openecomp.sdc.be.resources.data.InputValueData;
+import org.openecomp.sdc.be.resources.data.InputsData;
+import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
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;
-
@Component("input-operation")
public class InputsOperation extends AbstractOperation implements IInputsOperation {
@@ -48,67 +50,59 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
@Autowired
PropertyOperation propertyOperation;
- public <ElementDefinition> JanusGraphOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) {
-
- log.trace("Going to fetch elements under resource {}" , resourceId);
- JanusGraphOperationStatus
- resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements);
-
+ public <ElementDefinition> JanusGraphOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId,
+ List<ElementDefinition> elements,
+ NodeElementFetcher<ElementDefinition> singleNodeFetcher) {
+ log.trace("Going to fetch elements under resource {}", resourceId);
+ JanusGraphOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements);
if (resourceAttributesStatus != JanusGraphOperationStatus.OK) {
return resourceAttributesStatus;
}
-
Either<ImmutablePair<ResourceMetadataData, GraphEdge>, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class);
-
+ .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
+ ResourceMetadataData.class);
if (parentNodes.isRight()) {
JanusGraphOperationStatus parentNodesStatus = parentNodes.right().value();
if (parentNodesStatus != JanusGraphOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively",
+ "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR);
return parentNodesStatus;
}
}
-
if (parentNodes.isLeft()) {
ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value();
String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId();
JanusGraphOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher);
-
if (addParentIntStatus != JanusGraphOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR);
-
+ BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively",
+ "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR);
return addParentIntStatus;
}
}
return JanusGraphOperationStatus.OK;
}
-
@Override
public ImmutablePair<JanusGraphOperationStatus, String> findInputValue(String resourceInstanceId, String propertyId) {
-
log.debug("Going to check whether the property {} already added to resource instance {}", propertyId, resourceInstanceId);
-
Either<List<ComponentInstanceInput>, JanusGraphOperationStatus> getAllRes = getAllInputsOfResourceInstanceOnlyInputDefId(resourceInstanceId);
if (getAllRes.isRight()) {
JanusGraphOperationStatus status = getAllRes.right().value();
- log.trace("After fetching all properties of resource instance {}. Status is {}" ,resourceInstanceId, status);
+ log.trace("After fetching all properties of resource instance {}. Status is {}", resourceInstanceId, status);
return new ImmutablePair<>(status, null);
}
-
List<ComponentInstanceInput> list = getAllRes.left().value();
if (list != null) {
for (ComponentInstanceInput instanceProperty : list) {
String propertyUniqueId = instanceProperty.getUniqueId();
String valueUniqueUid = instanceProperty.getValueUniqueUid();
- log.trace("Go over property {} under resource instance {}. valueUniqueId = {}" ,propertyUniqueId, resourceInstanceId, valueUniqueUid);
+ log.trace("Go over property {} under resource instance {}. valueUniqueId = {}", propertyUniqueId, resourceInstanceId, valueUniqueUid);
if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) {
log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId);
return new ImmutablePair<>(JanusGraphOperationStatus.ALREADY_EXIST, valueUniqueUid);
}
}
}
-
return new ImmutablePair<>(JanusGraphOperationStatus.NOT_FOUND, null);
}
@@ -119,16 +113,13 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
* @return
*/
public Either<List<ComponentInstanceInput>, JanusGraphOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid) {
-
return getAllInputsOfResourceInstanceOnlyInputDefId(resourceInstanceUid, NodeTypeEnum.ResourceInstance);
-
}
- public Either<List<ComponentInstanceInput>, JanusGraphOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) {
-
+ public Either<List<ComponentInstanceInput>, JanusGraphOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid,
+ NodeTypeEnum instanceNodeType) {
Either<ComponentInstanceData, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, ComponentInstanceData.class);
-
if (findResInstanceRes.isRight()) {
JanusGraphOperationStatus status = findResInstanceRes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -136,42 +127,33 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
}
return Either.right(status);
}
-
Either<List<ImmutablePair<InputValueData, GraphEdge>>, JanusGraphOperationStatus> propertyImplNodes = janusGraphGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.INPUT_VALUE, NodeTypeEnum.InputValue, InputValueData.class);
-
+ .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.INPUT_VALUE,
+ NodeTypeEnum.InputValue, InputValueData.class);
if (propertyImplNodes.isRight()) {
JanusGraphOperationStatus status = propertyImplNodes.right().value();
return Either.right(status);
}
-
List<ImmutablePair<InputValueData, GraphEdge>> list = propertyImplNodes.left().value();
if (list == null || list.isEmpty()) {
return Either.right(JanusGraphOperationStatus.NOT_FOUND);
}
-
List<ComponentInstanceInput> result = new ArrayList<>();
-
-
for (ImmutablePair<InputValueData, GraphEdge> propertyValueDataPair : list) {
-
InputValueData propertyValueData = propertyValueDataPair.getLeft();
String propertyValueUid = propertyValueData.getUniqueId();
String value = propertyValueData.getValue();
-
Either<ImmutablePair<InputsData, GraphEdge>, JanusGraphOperationStatus> inputNodes = janusGraphGenericDao
- .getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), propertyValueData.getUniqueId(), GraphEdgeLabels.GET_INPUT, NodeTypeEnum.Input, InputsData.class);
-
+ .getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), propertyValueData.getUniqueId(), GraphEdgeLabels.GET_INPUT,
+ NodeTypeEnum.Input, InputsData.class);
if (inputNodes.isRight()) {
-
return Either.right(inputNodes.right().value());
}
-
InputsData input = inputNodes.left().value().left;
String inputId = input.getPropertyDataDefinition().getUniqueId();
-
Either<ImmutablePair<PropertyData, GraphEdge>, JanusGraphOperationStatus> propertyDefRes = janusGraphGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), propertyValueUid, GraphEdgeLabels.INPUT_IMPL, NodeTypeEnum.Property, PropertyData.class);
+ .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), propertyValueUid, GraphEdgeLabels.INPUT_IMPL,
+ NodeTypeEnum.Property, PropertyData.class);
if (propertyDefRes.isRight()) {
JanusGraphOperationStatus status = propertyDefRes.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -179,22 +161,18 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
}
return Either.right(status);
}
-
ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value();
PropertyData propertyData = propertyDefPair.left;
Either<Edge, JanusGraphOperationStatus> inputsEges = janusGraphGenericDao
.getIncomingEdgeByCriteria(propertyData, GraphEdgeLabels.INPUT, null);
if (inputsEges.isRight()) {
JanusGraphOperationStatus status = inputsEges.right().value();
-
return Either.right(status);
}
Edge edge = inputsEges.left().value();
- String inputName = (String) janusGraphGenericDao
- .getProperty(edge, GraphEdgePropertiesDictionary.NAME.getProperty());
-
- ComponentInstanceInput resourceInstanceProperty = new ComponentInstanceInput(propertyData.getPropertyDataDefinition(), inputId, value, propertyValueUid);
-
+ String inputName = (String) janusGraphGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.NAME.getProperty());
+ ComponentInstanceInput resourceInstanceProperty = new ComponentInstanceInput(propertyData.getPropertyDataDefinition(), inputId, value,
+ propertyValueUid);
resourceInstanceProperty.setName(inputName);
resourceInstanceProperty.setParentUniqueId(inputId);
resourceInstanceProperty.setValue(value);
@@ -202,24 +180,17 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
resourceInstanceProperty.setType(propertyData.getPropertyDataDefinition().getType());
resourceInstanceProperty.setSchema(propertyData.getPropertyDataDefinition().getSchema());
resourceInstanceProperty.setComponentInstanceId(resourceInstanceUid);
-
result.add(resourceInstanceProperty);
}
-
-
return Either.left(result);
}
@Override
public ComponentInstanceInput buildResourceInstanceInput(InputValueData propertyValueData, ComponentInstanceInput resourceInstanceInput) {
-
String value = propertyValueData.getValue();
String uid = propertyValueData.getUniqueId();
ComponentInstanceInput instanceProperty = new ComponentInstanceInput(resourceInstanceInput, value, uid);
instanceProperty.setPath(resourceInstanceInput.getPath());
-
return instanceProperty;
}
-
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java
index 87f01cd97e..a4d8ac9152 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java
@@ -17,17 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
import fj.data.Either;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -43,93 +50,67 @@ import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Component;
-import java.util.*;
-import java.util.Map.Entry;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
@Component("interface-operation")
public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation {
private static final Logger log = Logger.getLogger(InterfaceLifecycleOperation.class.getName());
private static final String FAILED_TO_FIND_OPERATION = "Failed to find operation {} on interface {}";
private static final String FAILED_TO_FIND_ARTIFACT = "Failed to add artifact {} to interface {}";
-
- public InterfaceLifecycleOperation() {
- super();
- }
-
@javax.annotation.Resource
private ArtifactOperation artifactOperation;
-
@javax.annotation.Resource
private JanusGraphGenericDao janusGraphGenericDao;
+ public InterfaceLifecycleOperation() {
+ super();
+ }
@Override
- public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction) {
-
+ public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId,
+ String interfaceName, boolean inTransaction) {
return createInterfaceOnResource(interf, resourceId, interfaceName, true, inTransaction);
-
}
- private Either<OperationData, JanusGraphOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName, Operation op, InterfaceData interfaceData) {
-
+ private Either<OperationData, JanusGraphOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName, Operation op,
+ InterfaceData interfaceData) {
op.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId((String) interfaceData.getUniqueId(), opName));
OperationData operationData = new OperationData(op);
-
log.debug("Before adding operation to graph {}", operationData);
- Either<OperationData, JanusGraphOperationStatus> createOpNodeResult = janusGraphGenericDao
- .createNode(operationData, OperationData.class);
+ Either<OperationData, JanusGraphOperationStatus> createOpNodeResult = janusGraphGenericDao.createNode(operationData, OperationData.class);
log.debug("After adding operation to graph {}", operationData);
-
if (createOpNodeResult.isRight()) {
JanusGraphOperationStatus opStatus = createOpNodeResult.right().value();
log.error("Failed to add operation {} to graph. status is {}", opName, opStatus);
return Either.right(opStatus);
}
-
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), opName);
Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props);
-
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createOpNodeResult.right().value();
log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceData.getUniqueId(), opName, operationStatus);
-
return Either.right(operationStatus);
}
-
return Either.left(createOpNodeResult.left().value());
-
}
private InterfaceDefinition convertInterfaceDataToInterfaceDefinition(InterfaceData interfaceData) {
-
log.debug("The object returned after create interface is {}", interfaceData);
-
return new InterfaceDefinition(interfaceData.getInterfaceDataDefinition());
-
}
private Operation convertOperationDataToOperation(OperationData operationData) {
-
log.debug("The object returned after create operation is {}", operationData);
-
return new Operation(operationData.getOperationDataDefinition());
-
}
- private Either<InterfaceData, JanusGraphOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId) {
+ private Either<InterfaceData, JanusGraphOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName,
+ String resourceId) {
InterfaceData interfaceData = new InterfaceData(interfaceInfo);
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(resourceId);
-
String interfaceNameSplitted = getShortInterfaceName(interfaceInfo);
interfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted));
-
Either<InterfaceData, JanusGraphOperationStatus> existInterface = janusGraphGenericDao
.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class);
if (existInterface.isRight()) {
@@ -140,18 +121,17 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
}
- private Either<InterfaceData, JanusGraphOperationStatus> createInterfaceNodeAndRelation(String interfaceName, String resourceId, InterfaceData interfaceData, ResourceMetadataData resourceData) {
+ private Either<InterfaceData, JanusGraphOperationStatus> createInterfaceNodeAndRelation(String interfaceName, String resourceId,
+ InterfaceData interfaceData,
+ ResourceMetadataData resourceData) {
log.debug("Before adding interface to graph {}", interfaceData);
- Either<InterfaceData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
- .createNode(interfaceData, InterfaceData.class);
+ Either<InterfaceData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(interfaceData, InterfaceData.class);
log.debug("After adding property to graph {}", interfaceData);
-
if (createNodeResult.isRight()) {
JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
log.error("Failed to add interface {} to graph. status is {}", interfaceName, operationStatus);
return Either.right(operationStatus);
}
-
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName);
Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
@@ -159,47 +139,42 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, interfaceName, operationStatus);
-
return Either.right(operationStatus);
}
-
return Either.left(createNodeResult.left().value());
}
- private Either<OperationData, JanusGraphOperationStatus> createOperationNodeAndRelation(String operationName, OperationData operationData, InterfaceData interfaceData) {
+ private Either<OperationData, JanusGraphOperationStatus> createOperationNodeAndRelation(String operationName, OperationData operationData,
+ InterfaceData interfaceData) {
log.debug("Before adding operation to graph {}", operationData);
- Either<OperationData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
- .createNode(operationData, OperationData.class);
+ Either<OperationData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(operationData, OperationData.class);
log.debug("After adding operation to graph {}", interfaceData);
-
if (createNodeResult.isRight()) {
JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
log.error("Failed to add interfoperationce {} to graph. status is {}", operationName, operationStatus);
return Either.right(operationStatus);
}
-
Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.NAME.getProperty(), operationName);
Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props);
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to associate operation {} to interface {} in graph. status is {}", operationName, interfaceData.getUniqueId(), operationStatus);
-
+ log.error("Failed to associate operation {} to interface {} in graph. status is {}", operationName, interfaceData.getUniqueId(),
+ operationStatus);
return Either.right(operationStatus);
}
-
return Either.left(createNodeResult.left().value());
}
-
@Override
public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceIdn, boolean recursively) {
return getAllInterfacesOfResource(resourceIdn, recursively, false);
}
@Override
- public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively, boolean inTransaction) {
+ public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively,
+ boolean inTransaction) {
Either<Map<String, InterfaceDefinition>, StorageOperationStatus> result = null;
Map<String, InterfaceDefinition> interfaces = new HashMap<>();
try {
@@ -208,7 +183,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
result = Either.right(StorageOperationStatus.INVALID_ID);
return result;
}
-
JanusGraphOperationStatus findInterfacesRes = JanusGraphOperationStatus.GENERAL_ERROR;
if (recursively) {
findInterfacesRes = findAllInterfacesRecursively(resourceId, interfaces);
@@ -237,9 +211,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
private JanusGraphOperationStatus findAllInterfacesNotRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) {
Either<List<ImmutablePair<InterfaceData, GraphEdge>>, JanusGraphOperationStatus> interfaceNodes = janusGraphGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.INTERFACE,
- NodeTypeEnum.Interface, InterfaceData.class);
-
+ .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface,
+ InterfaceData.class);
if (interfaceNodes.isRight()) {
JanusGraphOperationStatus status = interfaceNodes.right().value();
if (status != JanusGraphOperationStatus.NOT_FOUND) {
@@ -250,7 +223,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
if (interfaceList != null) {
for (ImmutablePair<InterfaceData, GraphEdge> interfacePair : interfaceList) {
String interfaceUniqueId = (String) interfacePair.getKey().getUniqueId();
- Either<String, JanusGraphOperationStatus> interfaceNameRes = getPropertyValueFromEdge(interfacePair.getValue(), GraphPropertiesDictionary.NAME);
+ Either<String, JanusGraphOperationStatus> interfaceNameRes = getPropertyValueFromEdge(interfacePair.getValue(),
+ GraphPropertiesDictionary.NAME);
if (interfaceNameRes.isRight()) {
log.error("The requirement name is missing on the edge of requirement {}", interfaceUniqueId);
return interfaceNameRes.right().value();
@@ -262,7 +236,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
log.error("Failed to get interface actions of interface {}", interfaceUniqueId);
return status;
}
-
InterfaceDefinition interfaceDefinition = interfaceDefRes.left().value();
if (interfaces.containsKey(interfaceName)) {
log.debug("The interface {} was already defined in dervied resource. add not overriden operations", interfaceName);
@@ -271,7 +244,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
} else {
interfaces.put(interfaceName, interfaceDefinition);
}
-
}
}
}
@@ -279,16 +251,13 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
public JanusGraphOperationStatus findAllInterfacesRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) {
- JanusGraphOperationStatus
- findAllInterfacesNotRecursively = findAllInterfacesNotRecursively(resourceId, interfaces);
+ JanusGraphOperationStatus findAllInterfacesNotRecursively = findAllInterfacesNotRecursively(resourceId, interfaces);
if (!findAllInterfacesNotRecursively.equals(JanusGraphOperationStatus.OK)) {
log.error("failed to get interfaces for resource {}. status is {}", resourceId, findAllInterfacesNotRecursively);
}
-
Either<ImmutablePair<ResourceMetadataData, GraphEdge>, JanusGraphOperationStatus> parentNodes = janusGraphGenericDao
.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
ResourceMetadataData.class);
-
if (parentNodes.isRight()) {
JanusGraphOperationStatus parentNodesStatus = parentNodes.right().value();
if (parentNodesStatus == JanusGraphOperationStatus.NOT_FOUND) {
@@ -302,12 +271,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
ImmutablePair<ResourceMetadataData, GraphEdge> parentNodePair = parentNodes.left().value();
String parentUniqueId = parentNodePair.getKey().getMetadataDataDefinition().getUniqueId();
JanusGraphOperationStatus addParentIntStatus = findAllInterfacesRecursively(parentUniqueId, interfaces);
-
if (addParentIntStatus != JanusGraphOperationStatus.OK) {
log.error("Failed to fetch all interfaces of resource {}", parentUniqueId);
return addParentIntStatus;
}
-
return JanusGraphOperationStatus.OK;
}
@@ -326,15 +293,12 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
private Either<InterfaceDefinition, JanusGraphOperationStatus> getNonRecursiveInterface(InterfaceData interfaceData) {
-
log.debug("Going to fetch the operations associate to interface {}", interfaceData.getUniqueId());
InterfaceDefinition interfaceDefinition = new InterfaceDefinition(interfaceData.getInterfaceDataDefinition());
-
String interfaceId = interfaceData.getUniqueId();
Either<List<ImmutablePair<OperationData, GraphEdge>>, JanusGraphOperationStatus> operationsRes = janusGraphGenericDao
.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), interfaceId, GraphEdgeLabels.INTERFACE_OPERATION,
NodeTypeEnum.InterfaceOperation, OperationData.class);
-
if (operationsRes.isRight()) {
JanusGraphOperationStatus status = operationsRes.right().value();
if (status != JanusGraphOperationStatus.NOT_FOUND) {
@@ -343,12 +307,12 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
return Either.left(interfaceDefinition);
}
}
-
List<ImmutablePair<OperationData, GraphEdge>> operationList = operationsRes.left().value();
if (operationList != null && !operationList.isEmpty()) {
for (ImmutablePair<OperationData, GraphEdge> operationPair : operationList) {
Operation operation = new Operation(operationPair.getKey().getOperationDataDefinition());
- Either<String, JanusGraphOperationStatus> operationNameRes = getPropertyValueFromEdge(operationPair.getValue(), GraphPropertiesDictionary.NAME);
+ Either<String, JanusGraphOperationStatus> operationNameRes = getPropertyValueFromEdge(operationPair.getValue(),
+ GraphPropertiesDictionary.NAME);
if (operationNameRes.isRight()) {
log.error("The operation name is missing on the edge of operation {}", operationPair.getKey().getUniqueId());
return Either.right(operationNameRes.right().value());
@@ -358,21 +322,19 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
interfaceDefinition.getOperations().put(operationName, operation);
}
}
-
return Either.left(interfaceDefinition);
}
private StorageOperationStatus findOperationImplementation(Operation operation) {
-
String operationId = operation.getUniqueId();
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsRes = artifactOperation.getArtifacts(operationId, NodeTypeEnum.InterfaceOperation, true);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsRes = artifactOperation
+ .getArtifacts(operationId, NodeTypeEnum.InterfaceOperation, true);
if (artifactsRes.isRight() || artifactsRes.left().value() == null) {
log.error("failed to get artifact from graph for operation id {}. status is {}", operationId, artifactsRes.right().value());
return artifactsRes.right().value();
} else {
Map<String, ArtifactDefinition> artifacts = artifactsRes.left().value();
Iterator<String> iter = artifacts.keySet().iterator();
-
if (iter.hasNext()) {
operation.setImplementation(artifacts.get(iter.next()));
}
@@ -395,44 +357,38 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
@Override
- public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf) {
-
+ public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName,
+ Operation interf) {
return updateInterfaceOperation(resourceId, interfaceName, operationName, interf, false);
}
@Override
- public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation operation, boolean inTransaction) {
-
+ public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName,
+ Operation operation, boolean inTransaction) {
return updateOperationOnGraph(operation, resourceId, interfaceName, operationName);
}
- private Either<Operation, StorageOperationStatus> updateOperationOnGraph(Operation operation, String resourceId, String interfaceName, String operationName) {
-
+ private Either<Operation, StorageOperationStatus> updateOperationOnGraph(Operation operation, String resourceId, String interfaceName,
+ String operationName) {
Either<List<ImmutablePair<InterfaceData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface,
InterfaceData.class);
-
if (childrenNodes.isRight()) {
return updateOperationFromParentNode(operation, resourceId, interfaceName, operationName);
-
} else {
return updateExistingOperation(resourceId, operation, interfaceName, operationName, childrenNodes);
-
}
-
}
- private Either<Operation, StorageOperationStatus> updateExistingOperation(String resourceId, Operation operation, String interfaceName, String operationName,
- Either<List<ImmutablePair<InterfaceData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes) {
+ private Either<Operation, StorageOperationStatus> updateExistingOperation(String resourceId, Operation operation, String interfaceName,
+ String operationName,
+ Either<List<ImmutablePair<InterfaceData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes) {
Operation newOperation = null;
StorageOperationStatus storageOperationStatus = StorageOperationStatus.GENERAL_ERROR;
-
for (ImmutablePair<InterfaceData, GraphEdge> interfaceDataNode : childrenNodes.left().value()) {
-
GraphEdge interfaceEdge = interfaceDataNode.getRight();
Map<String, Object> interfaceEdgeProp = interfaceEdge.getProperties();
InterfaceData interfaceData = interfaceDataNode.getKey();
-
if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceName)) {
Either<List<ImmutablePair<OperationData, GraphEdge>>, JanusGraphOperationStatus> operationRes = janusGraphGenericDao
.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(),
@@ -449,13 +405,15 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) {
ArtifactDefinition artifact = operation.getImplementationArtifact();
Either<ImmutablePair<ArtifactData, GraphEdge>, JanusGraphOperationStatus> artifactRes = janusGraphGenericDao
- .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) opData.getUniqueId(), GraphEdgeLabels.ARTIFACT_REF,
- NodeTypeEnum.ArtifactRef, ArtifactData.class);
+ .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) opData.getUniqueId(),
+ GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class);
Either<ArtifactDefinition, StorageOperationStatus> artStatus;
if (artifactRes.isRight()) {
- artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationPairEdge.getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true);
+ artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationPairEdge.getLeft().getUniqueId(),
+ NodeTypeEnum.InterfaceOperation, true, true);
} else {
- artStatus = artifactOperation.updateArifactOnResource(artifact, (String) operationPairEdge.getLeft().getUniqueId(), (String) artifactRes.left().value().getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true);
+ artStatus = artifactOperation.updateArifactOnResource(artifact, (String) operationPairEdge.getLeft().getUniqueId(),
+ (String) artifactRes.left().value().getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true);
}
if (artStatus.isRight()) {
janusGraphGenericDao.rollback();
@@ -464,11 +422,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
} else {
newOperation = this.convertOperationDataToOperation(opData);
newOperation.setImplementation(artStatus.left().value());
-
}
-
}
-
}
if (newOperation == null) {
Either<InterfaceData, JanusGraphOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName);
@@ -476,7 +431,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
log.debug("Interface {} not exist", interfaceName);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentInterfaceStatus.right().value()));
}
-
InterfaceData parentInterfaceData = parentInterfaceStatus.left().value();
Either<List<ImmutablePair<OperationData, GraphEdge>>, JanusGraphOperationStatus> opRes = janusGraphGenericDao
.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) parentInterfaceData.getUniqueId(),
@@ -484,7 +438,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
if (opRes.isRight()) {
log.error(FAILED_TO_FIND_OPERATION, operationName, interfaceName);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationRes.right().value()));
-
} else {
List<ImmutablePair<OperationData, GraphEdge>> parentOperations = opRes.left().value();
for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : parentOperations) {
@@ -492,29 +445,29 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
OperationData opData = operationPairEdge.getLeft();
Map<String, Object> opEdgeProp = opEdge.getProperties();
if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) {
- return copyAndCreateNewOperation(operation, interfaceName, operationName, null, interfaceData, operationRes, opData);
+ return copyAndCreateNewOperation(operation, interfaceName, operationName, null, interfaceData, operationRes,
+ opData);
}
}
}
-
}
-
}
-
} else {
// not found
storageOperationStatus = StorageOperationStatus.ARTIFACT_NOT_FOUND;
}
-
}
- if (newOperation == null)
+ if (newOperation == null) {
return Either.right(storageOperationStatus);
- else
+ } else {
return Either.left(newOperation);
+ }
}
- private Either<Operation, StorageOperationStatus> copyAndCreateNewOperation(Operation operation, String interfaceName, String operationName, Operation newOperation, InterfaceData interfaceData,
- Either<List<ImmutablePair<OperationData, GraphEdge>>, JanusGraphOperationStatus> operationRes, OperationData opData) {
+ private Either<Operation, StorageOperationStatus> copyAndCreateNewOperation(Operation operation, String interfaceName, String operationName,
+ Operation newOperation, InterfaceData interfaceData,
+ Either<List<ImmutablePair<OperationData, GraphEdge>>, JanusGraphOperationStatus> operationRes,
+ OperationData opData) {
OperationDataDefinition opDataInfo = opData.getOperationDataDefinition();
OperationDataDefinition newOperationInfo = new OperationDataDefinition(opDataInfo);
newOperationInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(interfaceData.getUniqueId(), operationName.toLowerCase()));
@@ -526,20 +479,21 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
ArtifactDefinition artifact = operation.getImplementationArtifact();
if (artifact != null) {
- Either<ArtifactDefinition, StorageOperationStatus> artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationStatus.left().value().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true);
+ Either<ArtifactDefinition, StorageOperationStatus> artStatus = artifactOperation
+ .addArifactToComponent(artifact, (String) operationStatus.left().value().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true);
if (artStatus.isRight()) {
janusGraphGenericDao.rollback();
log.error(FAILED_TO_FIND_ARTIFACT, operationName, interfaceName);
} else {
newOperation = this.convertOperationDataToOperation(opData);
newOperation.setImplementation(artStatus.left().value());
-
}
}
return Either.left(newOperation);
}
- private Either<Operation, StorageOperationStatus> updateOperationFromParentNode(Operation operation, String resourceId, String interfaceName, String operationName) {
+ private Either<Operation, StorageOperationStatus> updateOperationFromParentNode(Operation operation, String resourceId, String interfaceName,
+ String operationName) {
// Operation newOperation = null;
ResourceMetadataData resourceData = new ResourceMetadataData();
resourceData.getMetadataDataDefinition().setUniqueId(resourceId);
@@ -548,28 +502,25 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
log.debug("Interface {} not exist", interfaceName);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentInterfaceStatus.right().value()));
}
-
InterfaceData interfaceData = parentInterfaceStatus.left().value();
InterfaceDataDefinition intDataDefinition = interfaceData.getInterfaceDataDefinition();
InterfaceDataDefinition newInterfaceInfo = new InterfaceDataDefinition(intDataDefinition);
-
String interfaceNameSplitted = getShortInterfaceName(intDataDefinition);
-
newInterfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted));
InterfaceData updatedInterfaceData = new InterfaceData(newInterfaceInfo);
- Either<InterfaceData, JanusGraphOperationStatus> createStatus = createInterfaceNodeAndRelation(interfaceName, resourceId, updatedInterfaceData, resourceData);
+ Either<InterfaceData, JanusGraphOperationStatus> createStatus = createInterfaceNodeAndRelation(interfaceName, resourceId,
+ updatedInterfaceData, resourceData);
if (createStatus.isRight()) {
- log.debug("failed to create interface node {} on resource {}", interfaceName, resourceId);
+ log.debug("failed to create interface node {} on resource {}", interfaceName, resourceId);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createStatus.right().value()));
}
-
InterfaceData newInterfaceNode = createStatus.left().value();
Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
.createRelation(newInterfaceNode, interfaceData, GraphEdgeLabels.DERIVED_FROM, null);
if (createRelResult.isRight()) {
JanusGraphOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate interface {} to interface {} in graph. status is {}", interfaceData.getUniqueId(), newInterfaceNode.getUniqueId(), operationStatus);
-
+ log.error("Failed to associate interface {} to interface {} in graph. status is {}", interfaceData.getUniqueId(),
+ newInterfaceNode.getUniqueId(), operationStatus);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus));
}
Either<List<ImmutablePair<OperationData, GraphEdge>>, JanusGraphOperationStatus> operationRes = janusGraphGenericDao
@@ -578,7 +529,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
if (operationRes.isRight()) {
log.error(FAILED_TO_FIND_OPERATION, operationName, interfaceName);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationRes.right().value()));
-
} else {
List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value();
for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : operations) {
@@ -586,12 +536,12 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
OperationData opData = operationPairEdge.getLeft();
Map<String, Object> opEdgeProp = opEdge.getProperties();
if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) {
-
return copyAndCreateNewOperation(operation, interfaceName, operationName, null, // changed
- // from
- // newOperation
- newInterfaceNode, operationRes, opData);
+ // from
+
+ // newOperation
+ newInterfaceNode, operationRes, opData);
}
}
}
@@ -599,7 +549,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
private Either<InterfaceData, JanusGraphOperationStatus> findInterfaceOnParentNode(String resourceId, String interfaceName) {
-
Either<ImmutablePair<ResourceMetadataData, GraphEdge>, JanusGraphOperationStatus> parentRes = janusGraphGenericDao
.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
ResourceMetadataData.class);
@@ -608,50 +557,43 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
return Either.right(parentRes.right().value());
}
ImmutablePair<ResourceMetadataData, GraphEdge> parenNode = parentRes.left().value();
-
Either<List<ImmutablePair<InterfaceData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), parenNode.getKey().getMetadataDataDefinition().getUniqueId(),
GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class);
if (childrenNodes.isRight()) {
return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), interfaceName);
-
} else {
for (ImmutablePair<InterfaceData, GraphEdge> interfaceDataNode : childrenNodes.left().value()) {
-
GraphEdge interfaceEdge = interfaceDataNode.getRight();
Map<String, Object> interfaceEdgeProp = interfaceEdge.getProperties();
-
if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceName)) {
return Either.left(interfaceDataNode.getKey());
}
-
}
return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), interfaceName);
}
-
}
@Override
- public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction) {
+ public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId,
+ String interfaceName, boolean failIfExist,
+ boolean inTransaction) {
Either<InterfaceData, JanusGraphOperationStatus> status = addInterfaceToGraph(interf, interfaceName, resourceId);
if (status.isRight()) {
janusGraphGenericDao.rollback();
log.error("Failed to add interface {} to resource {}", interfaceName, resourceId);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status.right().value()));
} else {
-
if (!inTransaction) {
janusGraphGenericDao.commit();
}
InterfaceData interfaceData = status.left().value();
-
InterfaceDefinition interfaceDefResult = convertInterfaceDataToInterfaceDefinition(interfaceData);
Map<String, Operation> operations = interf.getOperationsMap();
if (operations != null && !operations.isEmpty()) {
Set<String> opNames = operations.keySet();
Map<String, Operation> newOperations = new HashMap<>();
for (String operationName : opNames) {
-
Operation op = operations.get(operationName);
Either<OperationData, JanusGraphOperationStatus> opStatus = addOperationToGraph(interf, operationName, op, interfaceData);
if (status.isRight()) {
@@ -663,10 +605,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
OperationData opData = opStatus.left().value();
Operation newOperation = this.convertOperationDataToOperation(opData);
-
ArtifactDefinition art = op.getImplementationArtifact();
if (art != null) {
- Either<ArtifactDefinition, StorageOperationStatus> artRes = artifactOperation.addArifactToComponent(art, (String) opData.getUniqueId(), NodeTypeEnum.InterfaceOperation, failIfExist, true);
+ Either<ArtifactDefinition, StorageOperationStatus> artRes = artifactOperation
+ .addArifactToComponent(art, (String) opData.getUniqueId(), NodeTypeEnum.InterfaceOperation, failIfExist, true);
if (artRes.isRight()) {
janusGraphGenericDao.rollback();
log.error(FAILED_TO_FIND_ARTIFACT, operationName, interfaceName);
@@ -682,12 +624,11 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
log.debug("The returned InterfaceDefintion is {}", interfaceDefResult);
return Either.left(interfaceDefResult);
}
-
}
@Override
- public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationId, boolean inTransaction) {
-
+ public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationId,
+ boolean inTransaction) {
Either<Operation, JanusGraphOperationStatus> status = removeOperationOnGraph(resourceId, interfaceName, operationId);
if (status.isRight()) {
if (!inTransaction) {
@@ -699,33 +640,26 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
if (!inTransaction) {
janusGraphGenericDao.commit();
}
-
Operation opDefResult = status.left().value();
log.debug("The returned Operation is {}", opDefResult);
return Either.left(opDefResult);
}
-
}
private Either<Operation, JanusGraphOperationStatus> removeOperationOnGraph(String resourceId, String interfaceName, String operationId) {
log.debug("Before deleting operation from graph {}", operationId);
-
Either<List<ImmutablePair<InterfaceData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface,
InterfaceData.class);
-
if (childrenNodes.isRight()) {
log.debug("Not found interface {}", interfaceName);
return Either.right(childrenNodes.right().value());
}
OperationData opData = null;
for (ImmutablePair<InterfaceData, GraphEdge> interfaceDataNode : childrenNodes.left().value()) {
-
GraphEdge interfaceEdge = interfaceDataNode.getRight();
Map<String, Object> interfaceEdgeProp = interfaceEdge.getProperties();
-
String interfaceSplitedName = splitType(interfaceName);
-
if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceSplitedName)) {
Either<List<ImmutablePair<OperationData, GraphEdge>>, JanusGraphOperationStatus> operationRes = janusGraphGenericDao
.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(),
@@ -735,19 +669,18 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
return Either.right(operationRes.right().value());
}
List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value();
-
for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : operations) {
-
opData = operationPairEdge.getLeft();
if (opData.getUniqueId().equals(operationId)) {
-
Either<ImmutablePair<ArtifactData, GraphEdge>, JanusGraphOperationStatus> artifactRes = janusGraphGenericDao
.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) operationPairEdge.getLeft().getUniqueId(),
GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class);
Either<ArtifactDefinition, StorageOperationStatus> arStatus = null;
if (artifactRes.isLeft()) {
ArtifactData arData = artifactRes.left().value().getKey();
- arStatus = artifactOperation.removeArifactFromResource((String) operationPairEdge.getLeft().getUniqueId(), (String) arData.getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true);
+ arStatus = artifactOperation
+ .removeArifactFromResource((String) operationPairEdge.getLeft().getUniqueId(), (String) arData.getUniqueId(),
+ NodeTypeEnum.InterfaceOperation, true, true);
if (arStatus.isRight()) {
log.debug("failed to delete artifact {}", arData.getUniqueId());
return Either.right(JanusGraphOperationStatus.INVALID_ID);
@@ -766,21 +699,18 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
if (operations.size() <= 1) {
Either<InterfaceData, JanusGraphOperationStatus> deleteInterfaceStatus = janusGraphGenericDao
- .deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDataNode.left.getUniqueId(), InterfaceData.class);
+ .deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDataNode.left.getUniqueId(),
+ InterfaceData.class);
if (deleteInterfaceStatus.isRight()) {
log.debug("failed to delete interface {}", interfaceDataNode.left.getUniqueId());
return Either.right(JanusGraphOperationStatus.INVALID_ID);
}
-
}
-
return Either.left(operation);
-
}
}
}
}
-
log.debug("Not found operation {}", interfaceName);
return Either.right(JanusGraphOperationStatus.INVALID_ID);
}
@@ -788,13 +718,11 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
private String splitType(String interfaceName) {
String interfaceSplittedName;
String[] packageName = interfaceName.split("\\.");
-
if (packageName.length == 0) {
interfaceSplittedName = interfaceName;
} else {
interfaceSplittedName = packageName[packageName.length - 1];
}
-
return interfaceSplittedName.toLowerCase();
}
@@ -815,44 +743,35 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf, boolean inTransaction) {
Either<InterfaceDefinition, StorageOperationStatus> result = null;
try {
-
InterfaceData interfaceData = new InterfaceData(interf);
interf.setUniqueId(interf.getType().toLowerCase());
-
Either<InterfaceData, JanusGraphOperationStatus> existInterface = janusGraphGenericDao
.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class);
-
if (existInterface.isLeft()) {
// already exist
log.debug("Interface type already exist {}", interfaceData);
result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS);
return result;
}
-
log.debug("Before adding interface type to graph {}", interfaceData);
- Either<InterfaceData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
- .createNode(interfaceData, InterfaceData.class);
+ Either<InterfaceData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(interfaceData, InterfaceData.class);
log.debug("After adding property type to graph {}", interfaceData);
-
if (createNodeResult.isRight()) {
JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
log.error("Failed to add interface {} to graph. status is {}", interf.getType(), operationStatus);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus));
return result;
}
-
InterfaceDefinition interfaceDefResult = convertInterfaceDataToInterfaceDefinition(interfaceData);
Map<String, Operation> operations = interf.getOperationsMap();
-
if (operations != null && !operations.isEmpty()) {
Map<String, Operation> newOperations = new HashMap<>();
-
for (Map.Entry<String, Operation> operation : operations.entrySet()) {
- Either<OperationData, JanusGraphOperationStatus> opStatus = addOperationToGraph(interf, operation.getKey(), operation.getValue(), interfaceData);
+ Either<OperationData, JanusGraphOperationStatus> opStatus = addOperationToGraph(interf, operation.getKey(), operation.getValue(),
+ interfaceData);
if (opStatus.isRight()) {
janusGraphGenericDao.rollback();
log.error("Failed to add operation {} to interface {}", operation.getKey(), interf.getType());
-
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(opStatus.right().value()));
return result;
} else {
@@ -876,7 +795,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
}
}
-
}
@Override
@@ -911,29 +829,23 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
@Override
public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfaceLifecycleTypes() {
-
- Either<List<InterfaceData>, JanusGraphOperationStatus> allInterfaceLifecycleTypes =
- janusGraphGenericDao
- .getByCriteria(NodeTypeEnum.Interface, Collections.emptyMap(), InterfaceData.class);
+ Either<List<InterfaceData>, JanusGraphOperationStatus> allInterfaceLifecycleTypes = janusGraphGenericDao
+ .getByCriteria(NodeTypeEnum.Interface, Collections.emptyMap(), InterfaceData.class);
if (allInterfaceLifecycleTypes.isRight()) {
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus
- (allInterfaceLifecycleTypes.right().value()));
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(allInterfaceLifecycleTypes.right().value()));
}
-
Map<String, InterfaceDefinition> interfaceTypes = new HashMap<>();
List<InterfaceData> interfaceDataList = allInterfaceLifecycleTypes.left().value();
- List<InterfaceDefinition> interfaceDefinitions = interfaceDataList.stream()
- .map(this::convertInterfaceDataToInterfaceDefinition)
+ List<InterfaceDefinition> interfaceDefinitions = interfaceDataList.stream().map(this::convertInterfaceDataToInterfaceDefinition)
.filter(interfaceDefinition -> interfaceDefinition.getUniqueId().equalsIgnoreCase((interfaceDefinition.getType())))
.collect(Collectors.toList());
-
for (InterfaceDefinition interfaceDefinition : interfaceDefinitions) {
- Either<List<ImmutablePair<OperationData, GraphEdge>>, JanusGraphOperationStatus>
- childrenNodes = janusGraphGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),
- interfaceDefinition.getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class);
+ Either<List<ImmutablePair<OperationData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
+ .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), interfaceDefinition.getUniqueId(),
+ GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class);
if (childrenNodes.isLeft()) {
Map<String, OperationDataDefinition> operationsDataDefinitionMap = new HashMap<>();
- for(ImmutablePair<OperationData, GraphEdge> operation : childrenNodes.left().value()) {
+ for (ImmutablePair<OperationData, GraphEdge> operation : childrenNodes.left().value()) {
OperationData operationData = operation.getLeft();
operationsDataDefinitionMap.put(operationData.getUniqueId(), operationData.getOperationDataDefinition());
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java
index 5aabc6402e..6032b4ad2e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import fj.data.Either;
@@ -39,7 +38,6 @@ import org.openecomp.sdc.common.zip.ZipUtils;
public class OnboardingClient {
private static final Logger log = Logger.getLogger(OnboardingClient.class.getName());
-
private static Properties downloadCsarHeaders = new Properties();
static {
@@ -48,41 +46,33 @@ public class OnboardingClient {
public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, String userId) {
String url = buildDownloadCsarUrl() + "/" + csarUuid;
-
Properties headers = new Properties();
if (downloadCsarHeaders != null) {
downloadCsarHeaders.forEach(headers::put);
}
-
if (userId != null) {
headers.put(Constants.USER_ID_HEADER, userId);
}
-
log.debug("Url for downloading csar is {}. Headers are {}", url, headers);
-
try {
- HttpResponse<byte []> httpResponse = HttpRequest.getAsByteArray(url, headers);
+ HttpResponse<byte[]> httpResponse = HttpRequest.getAsByteArray(url, headers);
log.debug("After fetching csar {}. Http return code is {}", csarUuid, httpResponse.getStatusCode());
-
switch (httpResponse.getStatusCode()) {
- case HttpStatus.SC_OK:
- byte[] data = httpResponse.getResponse();
- if (data != null && data.length > 0) {
- Map<String, byte[]> readZip = ZipUtils.readZip(data, false);
- return Either.left(readZip);
- } else {
- log.debug("Data received from rest is null or empty");
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
-
- case HttpStatus.SC_NOT_FOUND:
- return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
-
- default:
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ case HttpStatus.SC_OK:
+ byte[] data = httpResponse.getResponse();
+ if (data != null && data.length > 0) {
+ Map<String, byte[]> readZip = ZipUtils.readZip(data, false);
+ return Either.left(readZip);
+ } else {
+ log.debug("Data received from rest is null or empty");
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ case HttpStatus.SC_NOT_FOUND:
+ return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
+ default:
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
- }
- catch(Exception e) {
+ } catch (Exception e) {
log.debug("Request failed with exception", e);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
@@ -90,7 +80,6 @@ public class OnboardingClient {
public Either<String, StorageOperationStatus> getPackages(String userId) {
String url = buildDownloadCsarUrl();
-
Properties headers = new Properties();
headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
@@ -103,20 +92,19 @@ public class OnboardingClient {
try {
HttpResponse<String> httpResposne = HttpRequest.get(url, headers);
log.debug("After fetching packages. Http return code is {}", httpResposne.getStatusCode());
-
+
switch (httpResposne.getStatusCode()) {
- case HttpStatus.SC_OK:
- String data = httpResposne.getResponse();
- return Either.left(data);
-
- case HttpStatus.SC_NOT_FOUND:
- return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
-
- default:
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ case HttpStatus.SC_OK:
+ String data = httpResposne.getResponse();
+ return Either.left(data);
+
+ case HttpStatus.SC_NOT_FOUND:
+ return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
+
+ default:
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
- }
- catch(Exception e) {
+ } catch (Exception e) {
log.debug("Request failed with exception", e);
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
@@ -124,21 +112,17 @@ public class OnboardingClient {
/**
* Build the url for download CSAR
- *
+ * <p>
* E.g., http://0.0.0.0:8181/onboarding-api/v1.0/vendor-software-products/packages/
*
* @return
*/
public String buildDownloadCsarUrl() {
-
OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
-
String protocol = onboardingConfig.getProtocol();
String host = onboardingConfig.getHost();
Integer port = onboardingConfig.getPort();
String uri = onboardingConfig.getDownloadCsarUri();
-
return protocol + "://" + host + ":" + port + uri;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java
index 4be429f755..947b2168b9 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,35 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
import fj.data.Either;
-import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
+import java.util.Map;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
+import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.operations.StorageException;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Component;
-import java.util.Map;
-
@Component
public class OperationUtils {
- private final JanusGraphDao janusGraphDao;
-
private static final Logger logger = Logger.getLogger(OperationUtils.class.getName());
+ private final JanusGraphDao janusGraphDao;
public OperationUtils(JanusGraphDao janusGraphDao) {
this.janusGraphDao = janusGraphDao;
}
- public <T> T onJanusGraphOperationFailure(JanusGraphOperationStatus status) {
- janusGraphDao.rollback();
- throw new StorageException(status);
- }
-
- static Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> fillProperties(String uniqueId,
- PropertyOperation propertyOperation,
+ static Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> fillProperties(String uniqueId, PropertyOperation propertyOperation,
NodeTypeEnum nodeTypeEnum) {
-
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode =
- propertyOperation.findPropertiesOfNode(nodeTypeEnum, uniqueId);
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode = propertyOperation
+ .findPropertiesOfNode(nodeTypeEnum, uniqueId);
if (findPropertiesOfNode.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = findPropertiesOfNode.right().value();
- logger.debug("After looking for properties of vertex {}. status is {}", uniqueId,
- janusGraphOperationStatus);
+ logger.debug("After looking for properties of vertex {}. status is {}", uniqueId, janusGraphOperationStatus);
if (JanusGraphOperationStatus.NOT_FOUND.equals(janusGraphOperationStatus)) {
return Either.right(JanusGraphOperationStatus.OK);
} else {
@@ -66,4 +55,9 @@ public class OperationUtils {
return Either.left(findPropertiesOfNode.left().value());
}
}
+
+ public <T> T onJanusGraphOperationFailure(JanusGraphOperationStatus status) {
+ janusGraphDao.rollback();
+ throw new StorageException(status);
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java
index e8a74fe79d..2b3695fc13 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java
@@ -17,11 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
-import org.janusgraph.graphdb.query.JanusGraphPredicate;
+import static org.openecomp.sdc.be.dao.janusgraph.JanusGraphUtils.buildNotInPredicate;
+
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.janusgraph.graphdb.query.JanusGraphPredicate;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
@@ -39,18 +46,12 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import java.util.*;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.dao.janusgraph.JanusGraphUtils.buildNotInPredicate;
-
@Component("policy-type-operation")
public class PolicyTypeOperation extends AbstractOperation implements IPolicyTypeOperation {
private static final Logger log = Logger.getLogger(PolicyTypeOperation.class.getName());
private static final String CREATE_FLOW_CONTEXT = "CreatePolicyType";
private static final String GET_FLOW_CONTEXT = "GetPolicyType";
-
@Autowired
private PropertyOperation propertyOperation;
@Autowired
@@ -71,15 +72,16 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
Either<PolicyTypeDefinition, StorageOperationStatus> result;
Either<PolicyTypeData, StorageOperationStatus> eitherStatus = addPolicyTypeToGraph(policyTypeDef);
if (eitherStatus.isRight()) {
- BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, policyTypeDef.getType(), eitherStatus.right().value().name());
+ BeEcompErrorManager.getInstance()
+ .logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, policyTypeDef.getType(), eitherStatus.right().value().name());
result = Either.right(eitherStatus.right().value());
} else {
PolicyTypeData policyTypeData = eitherStatus.left().value();
String uniqueId = policyTypeData.getUniqueId();
Either<PolicyTypeDefinition, StorageOperationStatus> policyTypeRes = this.getPolicyTypeByUid(uniqueId);
-
if (policyTypeRes.isRight()) {
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, policyTypeDef.getType(), eitherStatus.right().value().name());
+ BeEcompErrorManager.getInstance()
+ .logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, policyTypeDef.getType(), eitherStatus.right().value().name());
}
result = policyTypeRes;
}
@@ -87,30 +89,26 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
}
@Override
- public Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition updatedPolicyType, PolicyTypeDefinition currPolicyType) {
+ public Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition updatedPolicyType,
+ PolicyTypeDefinition currPolicyType) {
log.debug("updating policy type {}", updatedPolicyType.getType());
return updatePolicyTypeOnGraph(updatedPolicyType, currPolicyType);
}
@Override
public List<PolicyTypeDefinition> getAllPolicyTypes(Set<String> excludedPolicyTypes) {
- Map<String, Map.Entry<JanusGraphPredicate, Object>> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(), excludedPolicyTypes);
- return janusGraphGenericDao
- .getByCriteriaWithPredicate(NodeTypeEnum.PolicyType, predicateCriteria, PolicyTypeData.class)
- .left()
- .map(this::convertPolicyTypesToDefinition)
- .left()
- .on(operationUtils::onJanusGraphOperationFailure);
+ Map<String, Map.Entry<JanusGraphPredicate, Object>> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(),
+ excludedPolicyTypes);
+ return janusGraphGenericDao.getByCriteriaWithPredicate(NodeTypeEnum.PolicyType, predicateCriteria, PolicyTypeData.class).left()
+ .map(this::convertPolicyTypesToDefinition).left().on(operationUtils::onJanusGraphOperationFailure);
}
private List<PolicyTypeDefinition> convertPolicyTypesToDefinition(List<PolicyTypeData> policiesTypes) {
return policiesTypes.stream().map(type -> new PolicyTypeDefinition(type.getPolicyTypeDataDefinition())).collect(Collectors.toList());
}
-
private Either<PolicyTypeData, StorageOperationStatus> addPolicyTypeToGraph(PolicyTypeDefinition policyTypeDef) {
log.debug("Got policy type {}", policyTypeDef);
-
String ptUniqueId = UniqueIdBuilder.buildPolicyTypeUid(policyTypeDef.getType(), policyTypeDef.getVersion(), "policytype");
PolicyTypeData policyTypeData = buildPolicyTypeData(policyTypeDef, ptUniqueId);
log.debug("Before adding policy type to graph. policyTypeData = {}", policyTypeData);
@@ -123,14 +121,13 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus));
}
List<PropertyDefinition> properties = policyTypeDef.getProperties();
- Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToPolicyType = propertyOperation.addPropertiesToElementType(ptUniqueId, NodeTypeEnum.PolicyType, properties);
+ Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToPolicyType = propertyOperation
+ .addPropertiesToElementType(ptUniqueId, NodeTypeEnum.PolicyType, properties);
if (addPropertiesToPolicyType.isRight()) {
log.error("Failed add properties {} to policy {}", properties, policyTypeDef.getType());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertiesToPolicyType.right().value()));
}
- return addDerivedFromRelation(policyTypeDef, ptUniqueId)
- .left()
- .map(updatedDerivedFrom -> eitherPolicyTypeData.left().value());
+ return addDerivedFromRelation(policyTypeDef, ptUniqueId).left().map(updatedDerivedFrom -> eitherPolicyTypeData.left().value());
}
private Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeByCriteria(String type, Map<String, Object> properties) {
@@ -140,68 +137,60 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
result = Either.right(StorageOperationStatus.INVALID_ID);
return result;
}
-
Either<List<PolicyTypeData>, JanusGraphOperationStatus> eitherPolicyData = janusGraphGenericDao
.getByCriteria(NodeTypeEnum.PolicyType, properties, PolicyTypeData.class);
if (eitherPolicyData.isRight()) {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherPolicyData.right().value()));
} else {
- PolicyTypeDataDefinition dataDefinition = eitherPolicyData.left().value().stream().map(PolicyTypeData::getPolicyTypeDataDefinition).findFirst().get();
+ PolicyTypeDataDefinition dataDefinition = eitherPolicyData.left().value().stream().map(PolicyTypeData::getPolicyTypeDataDefinition)
+ .findFirst().get();
result = getPolicyTypeByUid(dataDefinition.getUniqueId());
}
return result;
-
}
private Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeByUid(String uniqueId) {
log.debug("#getPolicyTypeByUid - fetching policy type with id {}", uniqueId);
- return janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), uniqueId, PolicyTypeData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
- .left()
- .bind(policyType -> createPolicyTypeDefinition(uniqueId, policyType));
+ return janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), uniqueId, PolicyTypeData.class).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus).left()
+ .bind(policyType -> createPolicyTypeDefinition(uniqueId, policyType));
}
private Either<PolicyTypeDefinition, StorageOperationStatus> createPolicyTypeDefinition(String uniqueId, PolicyTypeData policyTypeNode) {
PolicyTypeDefinition policyType = new PolicyTypeDefinition(policyTypeNode.getPolicyTypeDataDefinition());
- return fillDerivedFrom(uniqueId, policyType)
- .left()
- .map(derivedFrom -> fillProperties(uniqueId, policyType, derivedFrom))
- .left()
- .map(props -> policyType);
+ return fillDerivedFrom(uniqueId, policyType).left().map(derivedFrom -> fillProperties(uniqueId, policyType, derivedFrom)).left()
+ .map(props -> policyType);
}
- private Either<List<PropertyDefinition>, StorageOperationStatus> fillProperties(String uniqueId, PolicyTypeDefinition policyType, PolicyTypeData derivedFromNode) {
+ private Either<List<PropertyDefinition>, StorageOperationStatus> fillProperties(String uniqueId, PolicyTypeDefinition policyType,
+ PolicyTypeData derivedFromNode) {
log.debug("#fillProperties - fetching all properties for policy type {}", policyType.getType());
- return propertyOperation.findPropertiesOfNode(NodeTypeEnum.PolicyType, uniqueId)
- .right()
- .bind(this::handlePolicyTypeHasNoProperties)
- .left()
- .bind(propsMap -> fillDerivedFromProperties(policyType, derivedFromNode, new ArrayList<>(propsMap.values())));
+ return propertyOperation.findPropertiesOfNode(NodeTypeEnum.PolicyType, uniqueId).right().bind(this::handlePolicyTypeHasNoProperties).left()
+ .bind(propsMap -> fillDerivedFromProperties(policyType, derivedFromNode, new ArrayList<>(propsMap.values())));
}
- private Either<List<PropertyDefinition>, StorageOperationStatus> fillDerivedFromProperties(PolicyTypeDefinition policyType, PolicyTypeData derivedFromNode, List<PropertyDefinition> policyTypeDirectProperties) {
+ private Either<List<PropertyDefinition>, StorageOperationStatus> fillDerivedFromProperties(PolicyTypeDefinition policyType,
+ PolicyTypeData derivedFromNode,
+ List<PropertyDefinition> policyTypeDirectProperties) {
if (derivedFromNode == null) {
policyType.setProperties(policyTypeDirectProperties);
return Either.left(policyTypeDirectProperties);
}
log.debug("#fillDerivedFromProperties - fetching all properties of derived from chain for policy type {}", policyType.getType());
- return propertyOperation.getAllPropertiesRec(derivedFromNode.getUniqueId(), NodeTypeEnum.PolicyType, PolicyTypeData.class)
- .left()
- .map(derivedFromProps -> {policyTypeDirectProperties.addAll(derivedFromProps); return policyTypeDirectProperties;})
- .left()
- .map(allProps -> {policyType.setProperties(allProps);return allProps;});
+ return propertyOperation.getAllPropertiesRec(derivedFromNode.getUniqueId(), NodeTypeEnum.PolicyType, PolicyTypeData.class).left()
+ .map(derivedFromProps -> {
+ policyTypeDirectProperties.addAll(derivedFromProps);
+ return policyTypeDirectProperties;
+ }).left().map(allProps -> {
+ policyType.setProperties(allProps);
+ return allProps;
+ });
}
private Either<PolicyTypeData, StorageOperationStatus> fillDerivedFrom(String uniqueId, PolicyTypeDefinition policyType) {
log.debug("#fillDerivedFrom - fetching policy type {} derived node", policyType.getType());
- return derivedFromOperation.getDerivedFromChild(uniqueId, NodeTypeEnum.PolicyType, PolicyTypeData.class)
- .right()
- .bind(this::handleDerivedFromNotExist)
- .left()
- .map(derivedFrom -> setDerivedFrom(policyType, derivedFrom));
-
+ return derivedFromOperation.getDerivedFromChild(uniqueId, NodeTypeEnum.PolicyType, PolicyTypeData.class).right()
+ .bind(this::handleDerivedFromNotExist).left().map(derivedFrom -> setDerivedFrom(policyType, derivedFrom));
}
private Either<PolicyTypeData, StorageOperationStatus> handleDerivedFromNotExist(StorageOperationStatus err) {
@@ -226,43 +215,39 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
}
private PolicyTypeData buildPolicyTypeData(PolicyTypeDefinition policyTypeDefinition, String ptUniqueId) {
-
PolicyTypeData policyTypeData = new PolicyTypeData(policyTypeDefinition);
-
policyTypeData.getPolicyTypeDataDefinition().setUniqueId(ptUniqueId);
Long creationDate = policyTypeData.getPolicyTypeDataDefinition().getCreationTime();
if (creationDate == null) {
creationDate = System.currentTimeMillis();
}
-
policyTypeData.getPolicyTypeDataDefinition().setCreationTime(creationDate);
policyTypeData.getPolicyTypeDataDefinition().setModificationTime(creationDate);
return policyTypeData;
}
- private Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyTypeOnGraph(PolicyTypeDefinition updatedPolicyType, PolicyTypeDefinition currPolicyType) {
+ private Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyTypeOnGraph(PolicyTypeDefinition updatedPolicyType,
+ PolicyTypeDefinition currPolicyType) {
updatePolicyTypeData(updatedPolicyType, currPolicyType);
- return janusGraphGenericDao.updateNode(new PolicyTypeData(updatedPolicyType), PolicyTypeData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
- .left()
- .bind(updatedNode -> updatePolicyProperties(updatedPolicyType.getUniqueId(), updatedPolicyType.getProperties()))
- .left()
- .bind(updatedProperties -> updatePolicyDerivedFrom(updatedPolicyType, currPolicyType.getDerivedFrom()))
- .left()
- .map(updatedDerivedFrom -> updatedPolicyType);
+ return janusGraphGenericDao.updateNode(new PolicyTypeData(updatedPolicyType), PolicyTypeData.class).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus).left()
+ .bind(updatedNode -> updatePolicyProperties(updatedPolicyType.getUniqueId(), updatedPolicyType.getProperties())).left()
+ .bind(updatedProperties -> updatePolicyDerivedFrom(updatedPolicyType, currPolicyType.getDerivedFrom())).left()
+ .map(updatedDerivedFrom -> updatedPolicyType);
}
private Either<Map<String, PropertyData>, StorageOperationStatus> updatePolicyProperties(String policyId, List<PropertyDefinition> properties) {
log.debug("#updatePolicyProperties - updating policy type properties for policy type with id {}", policyId);
- return propertyOperation.deletePropertiesAssociatedToNode(NodeTypeEnum.PolicyType, policyId)
- .left()
- .bind(deleteProps -> addPropertiesToPolicy(policyId, properties));
+ return propertyOperation.deletePropertiesAssociatedToNode(NodeTypeEnum.PolicyType, policyId).left()
+ .bind(deleteProps -> addPropertiesToPolicy(policyId, properties));
}
- private Either<GraphRelation, StorageOperationStatus> updatePolicyDerivedFrom(PolicyTypeDefinition updatedPolicyType, String currDerivedFromPolicyType) {
+ private Either<GraphRelation, StorageOperationStatus> updatePolicyDerivedFrom(PolicyTypeDefinition updatedPolicyType,
+ String currDerivedFromPolicyType) {
String policyTypeId = updatedPolicyType.getUniqueId();
- log.debug("#updatePolicyDerivedFrom - updating policy derived from relation for policy type with id {}. old derived type {}. new derived type {}", policyTypeId, currDerivedFromPolicyType, updatedPolicyType.getDerivedFrom());
+ log.debug(
+ "#updatePolicyDerivedFrom - updating policy derived from relation for policy type with id {}. old derived type {}. new derived type {}",
+ policyTypeId, currDerivedFromPolicyType, updatedPolicyType.getDerivedFrom());
StorageOperationStatus deleteDerivedRelationStatus = deleteDerivedFromPolicyType(policyTypeId, currDerivedFromPolicyType);
if (deleteDerivedRelationStatus != StorageOperationStatus.OK) {
return Either.right(deleteDerivedRelationStatus);
@@ -275,27 +260,28 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
if (derivedFrom == null) {
return Either.left(null);
}
- log.debug("#addDerivedFromRelationBefore - adding derived from relation between policy type {} to its parent {}", policyTypeDef.getType(), derivedFrom);
- return this.getLatestPolicyTypeByType(derivedFrom)
- .left()
- .bind(derivedFromPolicy -> derivedFromOperation.addDerivedFromRelation(ptUniqueId, derivedFromPolicy.getUniqueId(), NodeTypeEnum.PolicyType));
+ log.debug("#addDerivedFromRelationBefore - adding derived from relation between policy type {} to its parent {}", policyTypeDef.getType(),
+ derivedFrom);
+ return this.getLatestPolicyTypeByType(derivedFrom).left().bind(
+ derivedFromPolicy -> derivedFromOperation.addDerivedFromRelation(ptUniqueId, derivedFromPolicy.getUniqueId(), NodeTypeEnum.PolicyType));
}
private StorageOperationStatus deleteDerivedFromPolicyType(String policyTypeId, String derivedFromType) {
if (derivedFromType == null) {
return StorageOperationStatus.OK;
}
- log.debug("#deleteDerivedFromPolicyType - deleting derivedFrom relation for policy type with id {} and its derived type {}", policyTypeId, derivedFromType);
- return getLatestPolicyTypeByType(derivedFromType)
- .either(derivedFromNode -> derivedFromOperation.removeDerivedFromRelation(policyTypeId, derivedFromNode.getUniqueId(), NodeTypeEnum.PolicyType),
- err -> err);
+ log.debug("#deleteDerivedFromPolicyType - deleting derivedFrom relation for policy type with id {} and its derived type {}", policyTypeId,
+ derivedFromType);
+ return getLatestPolicyTypeByType(derivedFromType).either(
+ derivedFromNode -> derivedFromOperation.removeDerivedFromRelation(policyTypeId, derivedFromNode.getUniqueId(), NodeTypeEnum.PolicyType),
+ err -> err);
}
- private Either<Map<String, PropertyData>, StorageOperationStatus> addPropertiesToPolicy(String policyTypeId, List<PropertyDefinition> properties) {
+ private Either<Map<String, PropertyData>, StorageOperationStatus> addPropertiesToPolicy(String policyTypeId,
+ List<PropertyDefinition> properties) {
log.debug("#addPropertiesToPolicy - adding policy type properties for policy type with id {}", policyTypeId);
- return propertyOperation.addPropertiesToElementType(policyTypeId, NodeTypeEnum.PolicyType, properties)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ return propertyOperation.addPropertiesToElementType(policyTypeId, NodeTypeEnum.PolicyType, properties).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
private void updatePolicyTypeData(PolicyTypeDefinition updatedTypeDefinition, PolicyTypeDefinition currTypeDefinition) {
@@ -303,5 +289,4 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
updatedTypeDefinition.setCreationTime(currTypeDefinition.getCreationTime());
updatedTypeDefinition.setModificationTime(System.currentTimeMillis());
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java
index f626c1d629..790646754d 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
import com.fasterxml.jackson.core.ObjectCodec;
@@ -33,9 +32,6 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphVertex;
-import org.janusgraph.core.JanusGraphVertexProperty;
import fj.data.Either;
import java.io.IOException;
import java.lang.reflect.Type;
@@ -59,6 +55,9 @@ import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphVertex;
+import org.janusgraph.core.JanusGraphVertexProperty;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
@@ -66,11 +65,11 @@ import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
@@ -103,514 +102,299 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-
@Component("property-operation")
public class PropertyOperation extends AbstractOperation implements IPropertyOperation {
- private static final String FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE = "Failed to fetch properties of data type {}";
- private static final String DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS = "Data type {} cannot be found in graph. status is {}";
- private static final String GOING_TO_EXECUTE_COMMIT_ON_GRAPH = "Going to execute commit on graph.";
- private static final String GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH = "Going to execute rollback on graph.";
- private static final String FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS = "Failed to associate resource {} to property {} in graph. status is {}";
- private static final String AFTER_ADDING_PROPERTY_TO_GRAPH = "After adding property to graph {}";
- private static final String BEFORE_ADDING_PROPERTY_TO_GRAPH = "Before adding property to graph {}";
- private static final String THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID = "The value {} of property from type {} is invalid";
- private DerivedFromOperation derivedFromOperation;
+
+ private static final String FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE = "Failed to fetch properties of data type {}";
+ private static final String DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS = "Data type {} cannot be found in graph. status is {}";
+ private static final String GOING_TO_EXECUTE_COMMIT_ON_GRAPH = "Going to execute commit on graph.";
+ private static final String GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH = "Going to execute rollback on graph.";
+ private static final String FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS = "Failed to associate resource {} to property {} in graph. status is {}";
+ private static final String AFTER_ADDING_PROPERTY_TO_GRAPH = "After adding property to graph {}";
+ private static final String BEFORE_ADDING_PROPERTY_TO_GRAPH = "Before adding property to graph {}";
+ private static final String THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID = "The value {} of property from type {} is invalid";
private static final String PROPERTY = "Property";
private static final String UPDATE_DATA_TYPE = "UpdateDataType";
+ private static Logger log = Logger.getLogger(PropertyOperation.class.getName());
+ private DerivedFromOperation derivedFromOperation;
- @Autowired
- public PropertyOperation(HealingJanusGraphGenericDao janusGraphGenericDao, DerivedFromOperation derivedFromOperation) {
- this.janusGraphGenericDao = janusGraphGenericDao;
- this.derivedFromOperation = derivedFromOperation;
- }
-
- private static Logger log = Logger.getLogger(PropertyOperation.class.getName());
-
- public PropertyDefinition convertPropertyDataToPropertyDefinition(PropertyData propertyDataResult, String propertyName, String resourceId) {
- log.debug("The object returned after create property is {}", propertyDataResult);
-
- PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition());
- propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints()));
- propertyDefResult.setName(propertyName);
-
- return propertyDefResult;
- }
-
- public static class PropertyConstraintSerialiser implements JsonSerializer<PropertyConstraint> {
-
- @Override
- public JsonElement serialize(PropertyConstraint src, Type typeOfSrc, JsonSerializationContext context) {
- JsonParser parser = new JsonParser();
- JsonObject result = new JsonObject();
- JsonArray jsonArray = new JsonArray();
- if (src instanceof InRangeConstraint) {
- InRangeConstraint rangeConstraint = (InRangeConstraint) src;
- jsonArray.add(parser.parse(rangeConstraint.getRangeMinValue()));
- jsonArray.add(parser.parse(rangeConstraint.getRangeMaxValue()));
- result.add("inRange", jsonArray);
- } else if (src instanceof GreaterThanConstraint) {
- GreaterThanConstraint greaterThanConstraint = (GreaterThanConstraint) src;
- jsonArray.add(parser.parse(greaterThanConstraint.getGreaterThan()));
- result.add("greaterThan", jsonArray);
- } else if (src instanceof LessOrEqualConstraint) {
- LessOrEqualConstraint lessOrEqualConstraint = (LessOrEqualConstraint) src;
- jsonArray.add(parser.parse(lessOrEqualConstraint.getLessOrEqual()));
- result.add("lessOrEqual", jsonArray);
- } else {
- log.warn("PropertyConstraint {} is not supported. Ignored.", src.getClass().getName());
- }
-
- return result;
- }
-
- }
-
- public static class PropertyConstraintDeserialiser implements JsonDeserializer<PropertyConstraint> {
-
- private static final String THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL = "The value of GreaterThanConstraint is null";
-
- @Override
- public PropertyConstraint deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
-
- PropertyConstraint propertyConstraint = null;
-
- Set<Entry<String, JsonElement>> set = json.getAsJsonObject().entrySet();
-
- if (set.size() == 1) {
- Entry<String, JsonElement> element = set.iterator().next();
- String key = element.getKey();
- JsonElement value = element.getValue();
-
- ConstraintType constraintType = ConstraintType.getByType(key);
- if (constraintType == null) {
- log.warn("ConstraintType was not found for constraint name:{}", key);
- } else {
- switch (constraintType) {
- case IN_RANGE:
-
- if (value != null) {
- if (value instanceof JsonArray) {
- JsonArray rangeArray = (JsonArray) value;
- if (rangeArray.size() != 2) {
- log.error("The range constraint content is invalid. value = {}", value);
- } else {
- InRangeConstraint rangeConstraint = new InRangeConstraint();
- String minValue = rangeArray.get(0).getAsString();
- String maxValue;
- JsonElement maxElement = rangeArray.get(1);
- if(maxElement.isJsonNull()){
- maxValue = String.valueOf(maxElement.getAsJsonNull());
- } else {
- maxValue = maxElement.getAsString();
- }
- rangeConstraint.setRangeMinValue(minValue);
- rangeConstraint.setRangeMaxValue(maxValue);
- propertyConstraint = rangeConstraint;
- }
- }
-
- } else {
- log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL);
- }
- break;
- case GREATER_THAN:
- if (value != null) {
- String asString = value.getAsString();
- log.debug("Before adding value to GreaterThanConstraint object. value = {}", asString);
- propertyConstraint = new GreaterThanConstraint(asString);
- break;
- } else {
- log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL);
- }
- break;
-
- case LESS_THAN:
- if (value != null) {
- String asString = value.getAsString();
- log.debug("Before adding value to LessThanConstraint object. value = {}", asString);
- propertyConstraint = new LessThanConstraint(asString);
- break;
- } else {
- log.warn("The value of LessThanConstraint is null");
- }
- break;
- case GREATER_OR_EQUAL:
- if (value != null) {
- String asString = value.getAsString();
- log.debug("Before adding value to GreaterThanConstraint object. value = {}", asString);
- propertyConstraint = new GreaterOrEqualConstraint(asString);
- break;
- } else {
- log.warn("The value of GreaterOrEqualConstraint is null");
- }
- break;
- case LESS_OR_EQUAL:
-
- if (value != null) {
- String asString = value.getAsString();
- log.debug("Before adding value to LessOrEqualConstraint object. value = {}", asString);
- propertyConstraint = new LessOrEqualConstraint(asString);
- } else {
- log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL);
- }
- break;
-
- case VALID_VALUES:
-
- if (value != null) {
- JsonArray rangeArray = (JsonArray) value;
- if (rangeArray.size() == 0) {
- log.error("The valid values constraint content is invalid. value = {}", value);
- } else {
- ValidValuesConstraint vvConstraint = new ValidValuesConstraint();
- List<String> validValues = new ArrayList<>();
- for (JsonElement jsonElement : rangeArray) {
- String item = jsonElement.getAsString();
- validValues.add(item);
- }
- vvConstraint.setValidValues(validValues);
- propertyConstraint = vvConstraint;
- }
- }
- break;
-
- case MIN_LENGTH:
- if (value != null) {
- int asInt = value.getAsInt();
- log.debug("Before adding value to Min Length object. value = {}", asInt);
- propertyConstraint = new MinLengthConstraint(asInt);
- break;
- } else {
- log.warn("The value of MinLengthConstraint is null");
- }
- break;
- default:
- log.warn("Key {} is not supported. Ignored.", key);
- }
- }
- }
-
- return propertyConstraint;
- }
-
- }
-
-
- public Either<PropertyData, StorageOperationStatus> addProperty(String propertyName, PropertyDefinition propertyDefinition, String resourceId) {
-
- Either<PropertyData, JanusGraphOperationStatus> either = addPropertyToGraph(propertyName, propertyDefinition, resourceId);
- if (either.isRight()) {
- StorageOperationStatus storageStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value());
- return Either.right(storageStatus);
- }
- return Either.left(either.left().value());
- }
-
- /**
- * @param propertyDefinition
- * @return
- */
- @Override
- public StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
-
- log.trace("Going to validate property type and value. {}", propertyDefinition);
-
- String propertyType = propertyDefinition.getType();
- String value = propertyDefinition.getDefaultValue();
-
- ToscaPropertyType type = getType(propertyType);
-
- if (type == null) {
-
- DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
- if (dataTypeDefinition == null) {
- log.debug("The type {} of property cannot be found.", propertyType);
- return StorageOperationStatus.INVALID_TYPE;
- }
+ @Autowired
+ public PropertyOperation(HealingJanusGraphGenericDao janusGraphGenericDao, DerivedFromOperation derivedFromOperation) {
+ this.janusGraphGenericDao = janusGraphGenericDao;
+ this.derivedFromOperation = derivedFromOperation;
+ }
+
+ public PropertyDefinition convertPropertyDataToPropertyDefinition(PropertyData propertyDataResult, String propertyName, String resourceId) {
+ log.debug("The object returned after create property is {}", propertyDataResult);
+ PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition());
+ propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints()));
+ propertyDefResult.setName(propertyName);
+ return propertyDefResult;
+ }
+ public Either<PropertyData, StorageOperationStatus> addProperty(String propertyName, PropertyDefinition propertyDefinition, String resourceId) {
+ Either<PropertyData, JanusGraphOperationStatus> either = addPropertyToGraph(propertyName, propertyDefinition, resourceId);
+ if (either.isRight()) {
+ StorageOperationStatus storageStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value());
+ return Either.right(storageStatus);
+ }
+ return Either.left(either.left().value());
+ }
+
+ /**
+ * @param propertyDefinition
+ * @return
+ */
+ @Override
+ public StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
+ log.trace("Going to validate property type and value. {}", propertyDefinition);
+ String propertyType = propertyDefinition.getType();
+ String value = propertyDefinition.getDefaultValue();
+ ToscaPropertyType type = getType(propertyType);
+ if (type == null) {
+ DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
+ if (dataTypeDefinition == null) {
+ log.debug("The type {} of property cannot be found.", propertyType);
+ return StorageOperationStatus.INVALID_TYPE;
+ }
return validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
+ }
+ String innerType = null;
+ Either<String, JanusGraphOperationStatus> checkInnerType = getInnerType(type, propertyDefinition::getSchema);
+ if (checkInnerType.isRight()) {
+ return StorageOperationStatus.INVALID_TYPE;
+ }
+ innerType = checkInnerType.left().value();
+ log.trace("After validating property type {}", propertyType);
+ boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
+ if (!isValidProperty) {
+ log.info(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type);
+ return StorageOperationStatus.INVALID_VALUE;
+ }
+ PropertyValueConverter converter = type.getConverter();
+ if (isEmptyValue(value)) {
+ log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
+ propertyDefinition.setDefaultValue(EMPTY_VALUE);
+ } else if (!isEmptyValue(value)) {
+ String convertedValue = converter.convert(value, innerType, dataTypes);
+ propertyDefinition.setDefaultValue(convertedValue);
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public Either<PropertyData, JanusGraphOperationStatus> addPropertyToGraph(String propertyName, PropertyDefinition propertyDefinition,
+ String resourceId) {
+ ResourceMetadataData resourceData = new ResourceMetadataData();
+ resourceData.getMetadataDataDefinition().setUniqueId(resourceId);
+ List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
+ propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName));
+ PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
+ log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
+ Either<PropertyData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(propertyData, PropertyData.class);
+ log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
+ if (createNodeResult.isRight()) {
+ JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
+ log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
+ return Either.right(operationStatus);
+ }
+ Map<String, Object> props = new HashMap<>();
+ props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
+ Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
+ .createRelation(resourceData, propertyData, GraphEdgeLabels.PROPERTY, props);
+ if (createRelResult.isRight()) {
+ JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
+ log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, operationStatus);
+ return Either.right(operationStatus);
+ }
+ return Either.left(createNodeResult.left().value());
+ }
+
+ public JanusGraphOperationStatus addPropertyToGraphByVertex(JanusGraphVertex metadataVertex, String propertyName,
+ PropertyDefinition propertyDefinition, String resourceId) {
+ List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
+ propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName));
+ PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
+ log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
+ Either<JanusGraphVertex, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(propertyData);
+ log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
+ if (createNodeResult.isRight()) {
+ JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
+ log.error("Failed to add property {} to graph. status is ", propertyName, operationStatus);
+ return operationStatus;
+ }
+ Map<String, Object> props = new HashMap<>();
+ props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
+ JanusGraphVertex propertyVertex = createNodeResult.left().value();
+ JanusGraphOperationStatus createRelResult = janusGraphGenericDao.createEdge(metadataVertex, propertyVertex, GraphEdgeLabels.PROPERTY, props);
+ if (!createRelResult.equals(JanusGraphOperationStatus.OK)) {
+ log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, createRelResult);
+ return createRelResult;
+ }
+ return createRelResult;
+ }
+
+ public JanusGraphGenericDao getJanusGraphGenericDao() {
+ return janusGraphGenericDao;
+ }
+
+ /**
+ * FOR TEST ONLY
+ *
+ * @param janusGraphGenericDao
+ */
+ public void setJanusGraphGenericDao(HealingJanusGraphGenericDao janusGraphGenericDao) {
+ this.janusGraphGenericDao = janusGraphGenericDao;
+ }
+
+ public Either<PropertyData, JanusGraphOperationStatus> deletePropertyFromGraph(String propertyId) {
+ log.debug("Before deleting property from graph {}", propertyId);
+ return janusGraphGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
+ }
+
+ public Either<PropertyData, StorageOperationStatus> updateProperty(String propertyId, PropertyDefinition newPropertyDefinition,
+ Map<String, DataTypeDefinition> dataTypes) {
+ StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes);
+ if (validateAndUpdateProperty != StorageOperationStatus.OK) {
+ return Either.right(validateAndUpdateProperty);
+ }
+ Either<PropertyData, JanusGraphOperationStatus> either = updatePropertyFromGraph(propertyId, newPropertyDefinition);
+ if (either.isRight()) {
+ StorageOperationStatus storageStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value());
+ return Either.right(storageStatus);
+ }
+ return Either.left(either.left().value());
+ }
+
+ public Either<PropertyData, JanusGraphOperationStatus> updatePropertyFromGraph(String propertyId, PropertyDefinition propertyDefinition) {
+ if (log.isDebugEnabled()) {
+ log.debug("Before updating property on graph {}", propertyId);
+ }
+ // get the original property data
+ Either<PropertyData, JanusGraphOperationStatus> statusProperty = janusGraphGenericDao
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
+ if (statusProperty.isRight()) {
+ log.debug("Problem while get property with id {}. Reason - {}", propertyId, statusProperty.right().value().name());
+ return Either.right(statusProperty.right().value());
+ }
+ PropertyData orgPropertyData = statusProperty.left().value();
+ PropertyDataDefinition orgPropertyDataDefinition = orgPropertyData.getPropertyDataDefinition();
+ // create new property data to update
+ PropertyData newPropertyData = new PropertyData();
+ newPropertyData.setPropertyDataDefinition(propertyDefinition);
+ PropertyDataDefinition newPropertyDataDefinition = newPropertyData.getPropertyDataDefinition();
+ // update the original property data with new values
+ if (orgPropertyDataDefinition.getDefaultValue() == null) {
+ orgPropertyDataDefinition.setDefaultValue(newPropertyDataDefinition.getDefaultValue());
+ } else {
+ if (!orgPropertyDataDefinition.getDefaultValue().equals(newPropertyDataDefinition.getDefaultValue())) {
+ orgPropertyDataDefinition.setDefaultValue(newPropertyDataDefinition.getDefaultValue());
+ }
+ }
+ if (orgPropertyDataDefinition.getDescription() == null) {
+ orgPropertyDataDefinition.setDescription(newPropertyDataDefinition.getDescription());
+ } else {
+ if (!orgPropertyDataDefinition.getDescription().equals(newPropertyDataDefinition.getDescription())) {
+ orgPropertyDataDefinition.setDescription(newPropertyDataDefinition.getDescription());
+ }
+ }
+ if (!orgPropertyDataDefinition.getType().equals(newPropertyDataDefinition.getType())) {
+ orgPropertyDataDefinition.setType(newPropertyDataDefinition.getType());
+ }
+ if (newPropertyData.getConstraints() != null) {
+ orgPropertyData.setConstraints(newPropertyData.getConstraints());
+ }
+ orgPropertyDataDefinition.setSchema(newPropertyDataDefinition.getSchema());
+ return janusGraphGenericDao.updateNode(orgPropertyData, PropertyData.class);
+ }
+
+ public Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType(String propertyName, PropertyDefinition propertyDefinition,
+ NodeTypeEnum nodeType, String uniqueId) {
+ List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
+ propertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(uniqueId, propertyName));
+ PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
+ if (log.isDebugEnabled()) {
+ log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
+ }
+ Either<PropertyData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(propertyData, PropertyData.class);
+ if (log.isDebugEnabled()) {
+ log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
+ }
+ if (createNodeResult.isRight()) {
+ JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
+ log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
+ return Either.right(operationStatus);
+ }
+ Map<String, Object> props = new HashMap<>();
+ props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
+ UniqueIdData uniqueIdData = new UniqueIdData(nodeType, uniqueId);
+ log.debug("Before associating {} to property {}", uniqueIdData, propertyName);
+ Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
+ .createRelation(uniqueIdData, propertyData, GraphEdgeLabels.PROPERTY, props);
+ if (createRelResult.isRight()) {
+ JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
+ log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, uniqueId, propertyName, operationStatus);
+ return Either.right(operationStatus);
+ }
+ return Either.left(createNodeResult.left().value());
+ }
- }
- String innerType = null;
-
- Either<String, JanusGraphOperationStatus> checkInnerType = getInnerType(type, propertyDefinition::getSchema);
- if (checkInnerType.isRight()) {
- return StorageOperationStatus.INVALID_TYPE;
- }
- innerType = checkInnerType.left().value();
-
- log.trace("After validating property type {}", propertyType);
-
- boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
- if (!isValidProperty) {
- log.info(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type);
- return StorageOperationStatus.INVALID_VALUE;
- }
-
- PropertyValueConverter converter = type.getConverter();
-
- if (isEmptyValue(value)) {
- log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
- propertyDefinition.setDefaultValue(EMPTY_VALUE);
- } else if (!isEmptyValue(value)) {
- String convertedValue = converter.convert(value, innerType, dataTypes);
- propertyDefinition.setDefaultValue(convertedValue);
- }
- return StorageOperationStatus.OK;
- }
-
- public Either<PropertyData, JanusGraphOperationStatus> addPropertyToGraph(String propertyName, PropertyDefinition propertyDefinition, String resourceId) {
-
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(resourceId);
-
- List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
-
- propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName));
- PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
-
- log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
- Either<PropertyData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
- .createNode(propertyData, PropertyData.class);
- log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
- if (createNodeResult.isRight()) {
- JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
- return Either.right(operationStatus);
- }
-
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
- Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
- .createRelation(resourceData, propertyData, GraphEdgeLabels.PROPERTY, props);
- if (createRelResult.isRight()) {
- JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
- log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, operationStatus);
- return Either.right(operationStatus);
- }
-
- return Either.left(createNodeResult.left().value());
-
- }
-
- public JanusGraphOperationStatus addPropertyToGraphByVertex(JanusGraphVertex metadataVertex, String propertyName, PropertyDefinition propertyDefinition, String resourceId) {
-
- List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
-
- propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName));
- PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
-
- log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
- Either<JanusGraphVertex, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(propertyData);
- log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
- if (createNodeResult.isRight()) {
- JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add property {} to graph. status is ", propertyName, operationStatus);
- return operationStatus;
- }
-
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
- JanusGraphVertex propertyVertex = createNodeResult.left().value();
- JanusGraphOperationStatus
- createRelResult = janusGraphGenericDao
- .createEdge(metadataVertex, propertyVertex, GraphEdgeLabels.PROPERTY, props);
- if (!createRelResult.equals(JanusGraphOperationStatus.OK)) {
- log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, createRelResult);
- return createRelResult;
- }
-
- return createRelResult;
-
- }
-
- public JanusGraphGenericDao getJanusGraphGenericDao() {
- return janusGraphGenericDao;
- }
-
- public Either<PropertyData, JanusGraphOperationStatus> deletePropertyFromGraph(String propertyId) {
- log.debug("Before deleting property from graph {}", propertyId);
- return janusGraphGenericDao
- .deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
- }
-
- public Either<PropertyData, StorageOperationStatus> updateProperty(String propertyId, PropertyDefinition newPropertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
-
- StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes);
- if (validateAndUpdateProperty != StorageOperationStatus.OK) {
- return Either.right(validateAndUpdateProperty);
- }
-
- Either<PropertyData, JanusGraphOperationStatus> either = updatePropertyFromGraph(propertyId, newPropertyDefinition);
- if (either.isRight()) {
- StorageOperationStatus storageStatus = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(either.right().value());
- return Either.right(storageStatus);
- }
- return Either.left(either.left().value());
- }
-
- public Either<PropertyData, JanusGraphOperationStatus> updatePropertyFromGraph(String propertyId, PropertyDefinition propertyDefinition) {
- if (log.isDebugEnabled())
- log.debug("Before updating property on graph {}", propertyId);
-
- // get the original property data
- Either<PropertyData, JanusGraphOperationStatus> statusProperty = janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
- if (statusProperty.isRight()) {
- log.debug("Problem while get property with id {}. Reason - {}", propertyId, statusProperty.right().value().name());
- return Either.right(statusProperty.right().value());
- }
- PropertyData orgPropertyData = statusProperty.left().value();
- PropertyDataDefinition orgPropertyDataDefinition = orgPropertyData.getPropertyDataDefinition();
-
- // create new property data to update
- PropertyData newPropertyData = new PropertyData();
- newPropertyData.setPropertyDataDefinition(propertyDefinition);
- PropertyDataDefinition newPropertyDataDefinition = newPropertyData.getPropertyDataDefinition();
-
- // update the original property data with new values
- if (orgPropertyDataDefinition.getDefaultValue() == null) {
- orgPropertyDataDefinition.setDefaultValue(newPropertyDataDefinition.getDefaultValue());
- } else {
- if (!orgPropertyDataDefinition.getDefaultValue().equals(newPropertyDataDefinition.getDefaultValue())) {
- orgPropertyDataDefinition.setDefaultValue(newPropertyDataDefinition.getDefaultValue());
- }
- }
- if (orgPropertyDataDefinition.getDescription() == null) {
- orgPropertyDataDefinition.setDescription(newPropertyDataDefinition.getDescription());
- } else {
- if (!orgPropertyDataDefinition.getDescription().equals(newPropertyDataDefinition.getDescription())) {
- orgPropertyDataDefinition.setDescription(newPropertyDataDefinition.getDescription());
- }
- }
- if (!orgPropertyDataDefinition.getType().equals(newPropertyDataDefinition.getType())) {
- orgPropertyDataDefinition.setType(newPropertyDataDefinition.getType());
- }
- if (newPropertyData.getConstraints() != null) {
- orgPropertyData.setConstraints(newPropertyData.getConstraints());
- }
- orgPropertyDataDefinition.setSchema(newPropertyDataDefinition.getSchema());
-
- return janusGraphGenericDao.updateNode(orgPropertyData, PropertyData.class);
- }
-
- /**
- * FOR TEST ONLY
- *
- * @param janusGraphGenericDao
- */
- public void setJanusGraphGenericDao(HealingJanusGraphGenericDao janusGraphGenericDao) {
- this.janusGraphGenericDao = janusGraphGenericDao;
- }
-
- public Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType(String propertyName, PropertyDefinition propertyDefinition, NodeTypeEnum nodeType, String uniqueId) {
-
- List<PropertyConstraint> constraints = propertyDefinition.getConstraints();
-
- propertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(uniqueId, propertyName));
- PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints));
-
- if (log.isDebugEnabled())
- log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData);
- Either<PropertyData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
- .createNode(propertyData, PropertyData.class);
- if (log.isDebugEnabled())
- log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData);
- if (createNodeResult.isRight()) {
- JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus);
- return Either.right(operationStatus);
- }
-
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName);
-
- UniqueIdData uniqueIdData = new UniqueIdData(nodeType, uniqueId);
- log.debug("Before associating {} to property {}", uniqueIdData, propertyName);
- Either<GraphRelation, JanusGraphOperationStatus> createRelResult = janusGraphGenericDao
- .createRelation(uniqueIdData, propertyData, GraphEdgeLabels.PROPERTY, props);
- if (createRelResult.isRight()) {
- JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
- log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, uniqueId, propertyName, operationStatus);
- return Either.right(operationStatus);
- }
-
- return Either.left(createNodeResult.left().value());
-
- }
-
- public Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode(NodeTypeEnum nodeType, String uniqueId) {
-
- Map<String, PropertyDefinition> resourceProps = new HashMap<>();
-
- Either<List<ImmutablePair<PropertyData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property,
- PropertyData.class);
-
- if (childrenNodes.isRight()) {
- JanusGraphOperationStatus operationStatus = childrenNodes.right().value();
- return Either.right(operationStatus);
- }
-
- List<ImmutablePair<PropertyData, GraphEdge>> values = childrenNodes.left().value();
- if (values != null) {
-
- for (ImmutablePair<PropertyData, GraphEdge> immutablePair : values) {
- GraphEdge edge = immutablePair.getValue();
- String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
- log.debug("Property {} is associated to node {}", propertyName, uniqueId);
- PropertyData propertyData = immutablePair.getKey();
- PropertyDefinition propertyDefinition = this.convertPropertyDataToPropertyDefinition(propertyData, propertyName, uniqueId);
- resourceProps.put(propertyName, propertyDefinition);
- }
-
- }
-
- log.debug("The properties associated to node {} are {}", uniqueId, resourceProps);
- return Either.left(resourceProps);
- }
+ public Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode(NodeTypeEnum nodeType, String uniqueId) {
+ Map<String, PropertyDefinition> resourceProps = new HashMap<>();
+ Either<List<ImmutablePair<PropertyData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
+ .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property,
+ PropertyData.class);
+ if (childrenNodes.isRight()) {
+ JanusGraphOperationStatus operationStatus = childrenNodes.right().value();
+ return Either.right(operationStatus);
+ }
+ List<ImmutablePair<PropertyData, GraphEdge>> values = childrenNodes.left().value();
+ if (values != null) {
+ for (ImmutablePair<PropertyData, GraphEdge> immutablePair : values) {
+ GraphEdge edge = immutablePair.getValue();
+ String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
+ log.debug("Property {} is associated to node {}", propertyName, uniqueId);
+ PropertyData propertyData = immutablePair.getKey();
+ PropertyDefinition propertyDefinition = this.convertPropertyDataToPropertyDefinition(propertyData, propertyName, uniqueId);
+ resourceProps.put(propertyName, propertyDefinition);
+ }
+ }
+ log.debug("The properties associated to node {} are {}", uniqueId, resourceProps);
+ return Either.left(resourceProps);
+ }
public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deletePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) {
- return deleteAllPropertiesAssociatedToNode(nodeType, uniqueId)
- .right()
- .bind(err -> err == StorageOperationStatus.OK ? Either.left(Collections.emptyMap()) : Either.right(err));
+ return deleteAllPropertiesAssociatedToNode(nodeType, uniqueId).right()
+ .bind(err -> err == StorageOperationStatus.OK ? Either.left(Collections.emptyMap()) : Either.right(err));
}
-
- public Either<Map<String, PropertyData>, JanusGraphOperationStatus> mergePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId, Map<String, PropertyDefinition> newProperties) {
+
+ public Either<Map<String, PropertyData>, JanusGraphOperationStatus> mergePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId,
+ Map<String, PropertyDefinition> newProperties) {
Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> oldPropertiesRes = findPropertiesOfNode(nodeType, uniqueId);
-
Map<String, PropertyDefinition> reallyNewProperties;
Map<String, PropertyData> unchangedPropsData;
-
if (oldPropertiesRes.isRight()) {
- JanusGraphOperationStatus err = oldPropertiesRes.right().value();
+ JanusGraphOperationStatus err = oldPropertiesRes.right().value();
if (err == JanusGraphOperationStatus.NOT_FOUND) {
reallyNewProperties = newProperties;
unchangedPropsData = Collections.emptyMap();
- }
- else {
+ } else {
return Either.right(err);
}
- }
- else {
+ } else {
Map<String, PropertyDefinition> oldProperties = oldPropertiesRes.left().value();
reallyNewProperties = collectReallyNewProperties(newProperties, oldProperties);
-
- for(Entry<String, PropertyDefinition> oldEntry: oldProperties.entrySet()) {
+ for (Entry<String, PropertyDefinition> oldEntry : oldProperties.entrySet()) {
String key = oldEntry.getKey();
- PropertyDefinition newPropDef = newProperties != null? newProperties.get(key): null;
+ PropertyDefinition newPropDef = newProperties != null ? newProperties.get(key) : null;
PropertyDefinition oldPropDef = oldEntry.getValue();
-
JanusGraphOperationStatus status = updateOldProperty(newPropDef, oldPropDef);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(status);
}
}
unchangedPropsData = oldProperties.entrySet().stream()
- .collect(Collectors.toMap(Entry::getKey, e-> new PropertyData(e.getValue(), null)));
+ .collect(Collectors.toMap(Entry::getKey, e -> new PropertyData(e.getValue(), null)));
}
-
-
// add other properties
return addPropertiesToElementType(nodeType, uniqueId, reallyNewProperties, unchangedPropsData);
}
@@ -620,10 +404,10 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
* @param oldProperties
* @return
*/
- private Map<String, PropertyDefinition> collectReallyNewProperties(Map<String, PropertyDefinition> newProperties, Map<String, PropertyDefinition> oldProperties) {
- return newProperties != null? newProperties.entrySet().stream()
- .filter(entry -> !oldProperties.containsKey(entry.getKey()))
- .collect(Collectors.toMap(Entry::getKey, Entry::getValue) ): null;
+ private Map<String, PropertyDefinition> collectReallyNewProperties(Map<String, PropertyDefinition> newProperties,
+ Map<String, PropertyDefinition> oldProperties) {
+ return newProperties != null ? newProperties.entrySet().stream().filter(entry -> !oldProperties.containsKey(entry.getKey()))
+ .collect(Collectors.toMap(Entry::getKey, Entry::getValue)) : null;
}
/**
@@ -634,20 +418,15 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
if (!isUpdateAllowed(newPropDef, oldPropDef)) {
return JanusGraphOperationStatus.MATCH_NOT_FOUND;
}
-
if (isUpdateRequired(newPropDef, oldPropDef)) {
modifyOldPropByNewOne(newPropDef, oldPropDef);
-
List<PropertyConstraint> constraints = oldPropDef.getConstraints();
PropertyData node = new PropertyData(oldPropDef, convertConstraintsToString(constraints));
- Either<PropertyData, JanusGraphOperationStatus> updateResult = janusGraphGenericDao
- .updateNode(node, PropertyData.class);
-
+ Either<PropertyData, JanusGraphOperationStatus> updateResult = janusGraphGenericDao.updateNode(node, PropertyData.class);
if (updateResult.isRight()) {
return updateResult.right().value();
}
}
-
return JanusGraphOperationStatus.OK;
}
@@ -660,18 +439,17 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
log.error("#mergePropertiesAssociatedToNode - Failed due attempt to delete the property with id {}", oldPropDef.getUniqueId());
return false;
}
-
- // If the property type is missing it's something that we could want to fix
- if ( oldPropDef.getType() != null && !oldPropDef.getType().equals(newPropDef.getType())) {
+ // If the property type is missing it's something that we could want to fix
+ if (oldPropDef.getType() != null && !oldPropDef.getType().equals(newPropDef.getType())) {
log.error("#mergePropertiesAssociatedToNode - Failed due attempt to change type of the property with id {}", oldPropDef.getUniqueId());
return false;
}
-
return true;
}
/**
* Update only fields which modification is permitted.
+ *
* @param newPropDef
* @param oldPropDef
*/
@@ -679,1735 +457,1496 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
oldPropDef.setDefaultValue(newPropDef.getDefaultValue());
oldPropDef.setDescription(newPropDef.getDescription());
oldPropDef.setRequired(newPropDef.isRequired());
-
// Type is updated to fix possible null type issue in janusGraph DB
oldPropDef.setType(newPropDef.getType());
}
-
private boolean isUpdateRequired(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) {
- return !StringUtils.equals(oldPropDef.getDefaultValue(), newPropDef.getDefaultValue()) ||
- !StringUtils.equals(oldPropDef.getDescription(), newPropDef.getDescription()) ||
- oldPropDef.isRequired() != newPropDef.isRequired();
+ return !StringUtils.equals(oldPropDef.getDefaultValue(), newPropDef.getDefaultValue()) || !StringUtils
+ .equals(oldPropDef.getDescription(), newPropDef.getDescription()) || oldPropDef.isRequired() != newPropDef.isRequired();
}
/**
- * Adds newProperties and returns in case of success (left part of Either)
- * map of all properties i. e. added ones and contained in unchangedPropsData
+ * Adds newProperties and returns in case of success (left part of Either) map of all properties i. e. added ones and contained in
+ * unchangedPropsData
+ *
* @param nodeType
* @param uniqueId
* @param newProperties
* @param unchangedPropsData
* @return
*/
- private Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(NodeTypeEnum nodeType, String uniqueId, Map<String, PropertyDefinition> newProperties, Map<String, PropertyData> unchangedPropsData) {
- return addPropertiesToElementType(uniqueId, nodeType, newProperties)
- .left()
- .map(m -> {
- m.putAll(unchangedPropsData);
- return m;
- });
- }
-
-
- public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) {
-
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesOfNodeRes = findPropertiesOfNode(nodeType, uniqueId);
-
- if (propertiesOfNodeRes.isRight()) {
- JanusGraphOperationStatus status = propertiesOfNodeRes.right().value();
- if (status == JanusGraphOperationStatus.NOT_FOUND) {
- return Either.right(StorageOperationStatus.OK);
- }
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
- }
-
- Map<String, PropertyDefinition> value = propertiesOfNodeRes.left().value();
- for (PropertyDefinition propertyDefinition : value.values()) {
-
- String propertyUid = propertyDefinition.getUniqueId();
- Either<PropertyData, JanusGraphOperationStatus> deletePropertyRes = deletePropertyFromGraph(propertyUid);
- if (deletePropertyRes.isRight()) {
- log.error("Failed to delete property with id {}", propertyUid);
- JanusGraphOperationStatus status = deletePropertyRes.right().value();
- if (status == JanusGraphOperationStatus.NOT_FOUND) {
- status = JanusGraphOperationStatus.INVALID_ID;
- }
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
- }
-
- }
-
- log.debug("The properties deleted from node {} are {}", uniqueId, value);
- return Either.left(value);
- }
-
-/**
- * Checks existence of a property with the same name belonging to the same resource
- * or existence of property with the same name and different type (including derived from hierarchy)
- * @param properties
- * @param resourceUid
- * @param propertyName
- * @param propertyType
- * @return
- */
- public boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName, String propertyType) {
- boolean result = false;
- if (!CollectionUtils.isEmpty(properties)) {
- for (PropertyDefinition propertyDefinition : properties) {
-
- if ( propertyDefinition.getName().equals(propertyName) &&
- (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) {
- result = true;
- break;
- }
- }
- }
- return result;
- }
-
- public ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
-
- if (rules == null || rules.isEmpty()) {
- return new ImmutablePair<>(null, true);
- }
-
- for (PropertyRule rule : rules) {
- String value = rule.getValue();
- Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
- if (updateResult.isRight()) {
- Boolean status = updateResult.right().value();
- if (!status) {
- return new ImmutablePair<>(value, status);
- }
- } else {
- String newValue = null;
- Object object = updateResult.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- rule.setValue(newValue);
- }
- }
-
- return new ImmutablePair<>(null, true);
- }
-
- public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) {
-
- List<PropertyRule> rules = resourceInstanceProperty.getRules();
- if (rules == null) {
- PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
- rules = new ArrayList<>();
- rules.add(propertyRule);
- } else {
- rules = sortRules(rules);
- }
-
- propertyValueData.setRules(rules);
- }
-
- private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) {
- List<String> path = resourceInstanceProperty.getPath();
- // FOR BC. Since old Property values on VFC/VF does not have rules on
- // graph.
- // Update could be done on one level only, thus we can use this
- // operation to avoid migration.
- if (path == null || path.isEmpty()) {
- path = new ArrayList<>();
- path.add(resourceInstanceId);
- }
- PropertyRule propertyRule = new PropertyRule();
- propertyRule.setRule(path);
- propertyRule.setValue(propertyValueData.getValue());
- return propertyRule;
- }
-
- private List<PropertyRule> sortRules(List<PropertyRule> rules) {
-
- // TODO: sort the rules by size and binary representation.
- // (x, y, .+) --> 110 6 priority 1
- // (x, .+, z) --> 101 5 priority 2
-
- return rules;
- }
-
- public ImmutablePair<JanusGraphOperationStatus, String> findPropertyValue(String resourceInstanceId, String propertyId) {
-
- log.debug("Going to check whether the property {} already added to resource instance {}", propertyId, resourceInstanceId);
-
- Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllRes = this.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceId);
- if (getAllRes.isRight()) {
- JanusGraphOperationStatus status = getAllRes.right().value();
- log.trace("After fetching all properties of resource instance {}. Status is {}", resourceInstanceId, status);
- return new ImmutablePair<>(status, null);
- }
-
- List<ComponentInstanceProperty> list = getAllRes.left().value();
- if (list != null) {
- for (ComponentInstanceProperty instanceProperty : list) {
- String propertyUniqueId = instanceProperty.getUniqueId();
- String valueUniqueUid = instanceProperty.getValueUniqueUid();
- log.trace("Go over property {} under resource instance {}. valueUniqueId = {}", propertyUniqueId, resourceInstanceId, valueUniqueUid);
- if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) {
- log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId);
- return new ImmutablePair<>(JanusGraphOperationStatus.ALREADY_EXIST, valueUniqueUid);
- }
- }
- }
-
- return new ImmutablePair<>(JanusGraphOperationStatus.NOT_FOUND, null);
- }
-
-
- public void updateRulesInPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) {
-
- List<PropertyRule> currentRules = propertyValueData.getRules();
-
- List<PropertyRule> rules = resourceInstanceProperty.getRules();
- // if rules are not supported.
- if (rules == null) {
-
- PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
- rules = new ArrayList<>();
- rules.add(propertyRule);
-
- if (currentRules != null) {
- rules = mergeRules(currentRules, rules);
- }
-
- } else {
- // Full mode. all rules are sent in update operation.
- rules = sortRules(rules);
- }
-
- propertyValueData.setRules(rules);
-
- }
-
- private List<PropertyRule> mergeRules(List<PropertyRule> currentRules, List<PropertyRule> newRules) {
-
- List<PropertyRule> mergedRules = new ArrayList<>();
-
- if (newRules == null || newRules.isEmpty()) {
- return currentRules;
- }
-
- for (PropertyRule rule : currentRules) {
- PropertyRule propertyRule = new PropertyRule(rule.getRule(), rule.getValue());
- mergedRules.add(propertyRule);
- }
-
- for (PropertyRule rule : newRules) {
- PropertyRule foundRule = findRuleInList(rule, mergedRules);
- if (foundRule != null) {
- foundRule.setValue(rule.getValue());
- } else {
- mergedRules.add(rule);
- }
- }
-
- return mergedRules;
- }
-
- private PropertyRule findRuleInList(PropertyRule rule, List<PropertyRule> rules) {
-
- if (rules == null || rules.isEmpty() || rule.getRule() == null || rule.getRule().isEmpty()) {
- return null;
- }
-
- PropertyRule foundRule = null;
- for (PropertyRule propertyRule : rules) {
- if (rule.getRuleSize() != propertyRule.getRuleSize()) {
- continue;
- }
- boolean equals = propertyRule.compareRule(rule);
- if (equals) {
- foundRule = propertyRule;
- break;
- }
- }
-
- return foundRule;
- }
-
- /**
- * return all properties associated to resource instance. The result does contains the property unique id but not its type, default value...
- *
- * @param resourceInstanceUid
- * @return
- */
- public Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(String resourceInstanceUid) {
-
- return getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceUid, NodeTypeEnum.ResourceInstance);
-
- }
-
- public Either<PropertyValueData, JanusGraphOperationStatus> removePropertyOfResourceInstance(String propertyValueUid, String resourceInstanceId) {
-
- Either<ComponentInstanceData, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class);
-
- if (findResInstanceRes.isRight()) {
- JanusGraphOperationStatus status = findResInstanceRes.right().value();
- if (status == JanusGraphOperationStatus.NOT_FOUND) {
- status = JanusGraphOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- Either<PropertyValueData, JanusGraphOperationStatus> findPropertyDefRes = janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, PropertyValueData.class);
-
- if (findPropertyDefRes.isRight()) {
- JanusGraphOperationStatus status = findPropertyDefRes.right().value();
- if (status == JanusGraphOperationStatus.NOT_FOUND) {
- status = JanusGraphOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- Either<GraphRelation, JanusGraphOperationStatus> relation = janusGraphGenericDao
- .getRelation(findResInstanceRes.left().value(), findPropertyDefRes.left().value(), GraphEdgeLabels.PROPERTY_VALUE);
- if (relation.isRight()) {
- // TODO: add error in case of error
- JanusGraphOperationStatus status = relation.right().value();
- if (status == JanusGraphOperationStatus.NOT_FOUND) {
- status = JanusGraphOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- Either<PropertyValueData, JanusGraphOperationStatus> deleteNode = janusGraphGenericDao
- .deleteNode(findPropertyDefRes.left().value(), PropertyValueData.class);
- if (deleteNode.isRight()) {
- return Either.right(deleteNode.right().value());
- }
- PropertyValueData value = deleteNode.left().value();
- return Either.left(value);
-
- }
-
- public Either<ComponentInstanceProperty, StorageOperationStatus> removePropertyValueFromResourceInstance(String propertyValueUid, String resourceInstanceId, boolean inTransaction) {
-
- Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
-
- try {
-
- Either<PropertyValueData, JanusGraphOperationStatus> eitherStatus = this.removePropertyOfResourceInstance(propertyValueUid, resourceInstanceId);
-
- if (eitherStatus.isRight()) {
- log.error("Failed to remove property value {} from resource instance {} in Graph. status is {}", propertyValueUid, resourceInstanceId, eitherStatus.right().value().name());
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
- return result;
- } else {
- PropertyValueData propertyValueData = eitherStatus.left().value();
-
- ComponentInstanceProperty propertyValueResult = new ComponentInstanceProperty();
- propertyValueResult.setUniqueId(resourceInstanceId);
- propertyValueResult.setValue(propertyValueData.getValue());
-
- log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
- result = Either.left(propertyValueResult);
- return result;
- }
- }
-
- finally {
- if (!inTransaction) {
- if (result == null || result.isRight()) {
- log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
- janusGraphGenericDao.rollback();
- } else {
- log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
- janusGraphGenericDao.commit();
- }
- }
- }
-
- }
-
- public ComponentInstanceProperty buildResourceInstanceProperty(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty) {
-
- String value = propertyValueData.getValue();
- String uid = propertyValueData.getUniqueId();
- ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(resourceInstanceProperty, value, uid);
- instanceProperty.setPath(resourceInstanceProperty.getPath());
-
- return instanceProperty;
- }
-
-
- public static class PropertyConstraintJacksonDeserializer extends com.fasterxml.jackson.databind.JsonDeserializer<PropertyConstraint> {
-
- @Override
- public PropertyConstraint deserialize(com.fasterxml.jackson.core.JsonParser json, DeserializationContext context) throws IOException {
- ObjectCodec oc = json.getCodec();
- JsonNode node = oc.readTree(json);
- return null;
- }
- }
-
- @Override
- public boolean isPropertyDefaultValueValid(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
- if (propertyDefinition == null) {
- return false;
- }
- String innerType = null;
- String propertyType = propertyDefinition.getType();
- ToscaPropertyType type = getType(propertyType);
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = propertyDefinition.getSchema();
- if (def == null) {
- return false;
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- return false;
- }
- innerType = propDef.getType();
- }
- String value = propertyDefinition.getDefaultValue();
- if (type != null) {
- return isValidValue(type, value, innerType, dataTypes);
- } else {
- log.trace("The given type {} is not a pre defined one.", propertyType);
-
- DataTypeDefinition foundDt = dataTypes.get(propertyType);
- if (foundDt != null) {
- return isValidComplexValue(foundDt, value, dataTypes);
- } else {
- return false;
- }
- }
- }
-
- public boolean isPropertyTypeValid(IComplexDefaultValue property) {
-
- if (property == null) {
- return false;
- }
-
- if (ToscaPropertyType.isValidType(property.getType()) == null) {
-
- Either<Boolean, JanusGraphOperationStatus> definedInDataTypes = isDefinedInDataTypes(property.getType());
-
- if (definedInDataTypes.isRight()) {
- return false;
- } else {
- Boolean isExist = definedInDataTypes.left().value();
- return isExist.booleanValue();
- }
-
- }
- return true;
- }
-
- @Override
- public ImmutablePair<String, Boolean> isPropertyInnerTypeValid(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
-
- if (property == null) {
- return new ImmutablePair<>(null, false);
- }
-
- SchemaDefinition schema;
- PropertyDataDefinition innerProp;
- String innerType = null;
- if ((schema = property.getSchema()) != null) {
- if ((innerProp = schema.getProperty()) != null) {
- innerType = innerProp.getType();
- }
- }
-
- ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
-
- if (innerToscaType == null) {
- DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
- if (dataTypeDefinition == null) {
- log.debug("The inner type {} is not a data type.", innerType);
- return new ImmutablePair<>(innerType, false);
- } else {
- log.debug("The inner type {} is a data type. Data type definition is {}", innerType, dataTypeDefinition);
- }
- }
-
- return new ImmutablePair<>(innerType, true);
- }
-
- private boolean isValidComplexValue(DataTypeDefinition foundDt, String value, Map<String, DataTypeDefinition> dataTypes) {
- ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter.validateAndUpdate(value, foundDt, dataTypes);
-
- log.trace("The result after validating complex value of type {} is {}", foundDt.getName(), validateAndUpdate);
-
- return validateAndUpdate.right.booleanValue();
-
- }
-
- public Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) {
-
- Either<JanusGraphVertex, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
- .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid);
-
- if (findResInstanceRes.isRight()) {
- JanusGraphOperationStatus status = findResInstanceRes.right().value();
- if (status == JanusGraphOperationStatus.NOT_FOUND) {
- status = JanusGraphOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- Either<List<ImmutablePair<JanusGraphVertex, Edge>>, JanusGraphOperationStatus> propertyImplNodes = janusGraphGenericDao
- .getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.PROPERTY_VALUE);
-
- if (propertyImplNodes.isRight()) {
- JanusGraphOperationStatus status = propertyImplNodes.right().value();
- return Either.right(status);
- }
-
- List<ImmutablePair<JanusGraphVertex, Edge>> list = propertyImplNodes.left().value();
- if (list == null || list.isEmpty()) {
- return Either.right(JanusGraphOperationStatus.NOT_FOUND);
- }
-
- List<ComponentInstanceProperty> result = new ArrayList<>();
- for (ImmutablePair<JanusGraphVertex, Edge> propertyValue : list) {
- JanusGraphVertex propertyValueDataVertex = propertyValue.getLeft();
- String propertyValueUid = (String) janusGraphGenericDao
- .getProperty(propertyValueDataVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- String value = (String) janusGraphGenericDao
- .getProperty(propertyValueDataVertex, GraphPropertiesDictionary.VALUE.getProperty());
-
- ImmutablePair<JanusGraphVertex, Edge> propertyDefPair = janusGraphGenericDao
- .getChildVertex(propertyValueDataVertex, GraphEdgeLabels.PROPERTY_IMPL);
- if (propertyDefPair == null) {
- return Either.right(JanusGraphOperationStatus.NOT_FOUND);
- }
-
- Map<String, Object> properties = janusGraphGenericDao.getProperties(propertyValueDataVertex);
- PropertyValueData propertyValueData = GraphElementFactory.createElement(NodeTypeEnum.PropertyValue.getName(), GraphElementTypeEnum.Node, properties, PropertyValueData.class);
- String propertyUniqueId = (String) janusGraphGenericDao
- .getProperty(propertyDefPair.left, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
-
- ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty();
- // set property original unique id
- resourceInstanceProperty.setUniqueId(propertyUniqueId);
- // set resource id
- // TODO: esofer add resource id
- resourceInstanceProperty.setParentUniqueId(null);
- // set value
- resourceInstanceProperty.setValue(value);
- // set property value unique id
- resourceInstanceProperty.setValueUniqueUid(propertyValueUid);
- // set rules
- resourceInstanceProperty.setRules(propertyValueData.getRules());
-
- result.add(resourceInstanceProperty);
- }
-
- return Either.left(result);
- }
-
- /**
- * Find the default value from the list of component instances. Start the search from the second component instance
- *
- * @param pathOfComponentInstances
- * @param propertyUniqueId
- * @param defaultValue
- * @return
- */
- public Either<String, JanusGraphOperationStatus> findDefaultValueFromSecondPosition(List<String> pathOfComponentInstances, String propertyUniqueId, String defaultValue) {
+ private Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(NodeTypeEnum nodeType, String uniqueId,
+ Map<String, PropertyDefinition> newProperties,
+ Map<String, PropertyData> unchangedPropsData) {
+ return addPropertiesToElementType(uniqueId, nodeType, newProperties).left().map(m -> {
+ m.putAll(unchangedPropsData);
+ return m;
+ });
+ }
- log.trace("In find default value: path= {} propertyUniqId={} defaultValue= {}", pathOfComponentInstances, propertyUniqueId, defaultValue);
+ public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType,
+ String uniqueId) {
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesOfNodeRes = findPropertiesOfNode(nodeType, uniqueId);
+ if (propertiesOfNodeRes.isRight()) {
+ JanusGraphOperationStatus status = propertiesOfNodeRes.right().value();
+ if (status == JanusGraphOperationStatus.NOT_FOUND) {
+ return Either.right(StorageOperationStatus.OK);
+ }
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
+ }
+ Map<String, PropertyDefinition> value = propertiesOfNodeRes.left().value();
+ for (PropertyDefinition propertyDefinition : value.values()) {
+ String propertyUid = propertyDefinition.getUniqueId();
+ Either<PropertyData, JanusGraphOperationStatus> deletePropertyRes = deletePropertyFromGraph(propertyUid);
+ if (deletePropertyRes.isRight()) {
+ log.error("Failed to delete property with id {}", propertyUid);
+ JanusGraphOperationStatus status = deletePropertyRes.right().value();
+ if (status == JanusGraphOperationStatus.NOT_FOUND) {
+ status = JanusGraphOperationStatus.INVALID_ID;
+ }
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
+ }
+ }
+ log.debug("The properties deleted from node {} are {}", uniqueId, value);
+ return Either.left(value);
+ }
- if (pathOfComponentInstances == null || pathOfComponentInstances.size() < 2) {
- return Either.left(defaultValue);
- }
+ /**
+ * Checks existence of a property with the same name belonging to the same resource or existence of property with the same name and different type
+ * (including derived from hierarchy)
+ *
+ * @param properties
+ * @param resourceUid
+ * @param propertyName
+ * @param propertyType
+ * @return
+ */
+ public boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName, String propertyType) {
+ boolean result = false;
+ if (!CollectionUtils.isEmpty(properties)) {
+ for (PropertyDefinition propertyDefinition : properties) {
+ if (propertyDefinition.getName().equals(propertyName) && (propertyDefinition.getParentUniqueId().equals(resourceUid)
+ || !propertyDefinition.getType().equals(propertyType))) {
+ result = true;
+ break;
+ }
+ }
+ }
+ return result;
+ }
+
+ public ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType,
+ Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
+ if (rules == null || rules.isEmpty()) {
+ return new ImmutablePair<>(null, true);
+ }
+ for (PropertyRule rule : rules) {
+ String value = rule.getValue();
+ Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
+ if (updateResult.isRight()) {
+ Boolean status = updateResult.right().value();
+ if (!status) {
+ return new ImmutablePair<>(value, status);
+ }
+ } else {
+ String newValue = null;
+ Object object = updateResult.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ rule.setValue(newValue);
+ }
+ }
+ return new ImmutablePair<>(null, true);
+ }
+
+ public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty,
+ String resourceInstanceId) {
+ List<PropertyRule> rules = resourceInstanceProperty.getRules();
+ if (rules == null) {
+ PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
+ rules = new ArrayList<>();
+ rules.add(propertyRule);
+ } else {
+ rules = sortRules(rules);
+ }
+ propertyValueData.setRules(rules);
+ }
- String result = defaultValue;
+ private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty,
+ String resourceInstanceId) {
+ List<String> path = resourceInstanceProperty.getPath();
+ // FOR BC. Since old Property values on VFC/VF does not have rules on
- for (int i = 1; i < pathOfComponentInstances.size(); i++) {
- String compInstanceId = pathOfComponentInstances.get(i);
+ // graph.
- Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> propertyValuesResult = this.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(compInstanceId, NodeTypeEnum.ResourceInstance);
+ // Update could be done on one level only, thus we can use this
- log.trace("After fetching properties values of component instance {}. {}", compInstanceId, propertyValuesResult);
+ // operation to avoid migration.
+ if (path == null || path.isEmpty()) {
+ path = new ArrayList<>();
+ path.add(resourceInstanceId);
+ }
+ PropertyRule propertyRule = new PropertyRule();
+ propertyRule.setRule(path);
+ propertyRule.setValue(propertyValueData.getValue());
+ return propertyRule;
+ }
- if (propertyValuesResult.isRight()) {
- JanusGraphOperationStatus status = propertyValuesResult.right().value();
- if (status != JanusGraphOperationStatus.NOT_FOUND) {
- return Either.right(status);
- } else {
- continue;
- }
- }
+ private List<PropertyRule> sortRules(List<PropertyRule> rules) {
+ // TODO: sort the rules by size and binary representation.
- ComponentInstanceProperty foundCompInstanceProperty = fetchByPropertyUid(propertyValuesResult.left().value(), propertyUniqueId);
- log.trace("After finding the component instance property on{} . {}", compInstanceId, foundCompInstanceProperty);
+ // (x, y, .+) --> 110 6 priority 1
- if (foundCompInstanceProperty == null) {
- continue;
- }
+ // (x, .+, z) --> 101 5 priority 2
+ return rules;
+ }
- List<PropertyRule> rules = getOrBuildRulesIfNotExists(pathOfComponentInstances.size() - i, pathOfComponentInstances.get(i), foundCompInstanceProperty.getRules(), foundCompInstanceProperty.getValue());
+ public ImmutablePair<JanusGraphOperationStatus, String> findPropertyValue(String resourceInstanceId, String propertyId) {
+ log.debug("Going to check whether the property {} already added to resource instance {}", propertyId, resourceInstanceId);
+ Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllRes = this
+ .getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceId);
+ if (getAllRes.isRight()) {
+ JanusGraphOperationStatus status = getAllRes.right().value();
+ log.trace("After fetching all properties of resource instance {}. Status is {}", resourceInstanceId, status);
+ return new ImmutablePair<>(status, null);
+ }
+ List<ComponentInstanceProperty> list = getAllRes.left().value();
+ if (list != null) {
+ for (ComponentInstanceProperty instanceProperty : list) {
+ String propertyUniqueId = instanceProperty.getUniqueId();
+ String valueUniqueUid = instanceProperty.getValueUniqueUid();
+ log.trace("Go over property {} under resource instance {}. valueUniqueId = {}", propertyUniqueId, resourceInstanceId, valueUniqueUid);
+ if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) {
+ log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId);
+ return new ImmutablePair<>(JanusGraphOperationStatus.ALREADY_EXIST, valueUniqueUid);
+ }
+ }
+ }
+ return new ImmutablePair<>(JanusGraphOperationStatus.NOT_FOUND, null);
+ }
- log.trace("Rules of property {} on component instance {} are {}", propertyUniqueId, compInstanceId, rules);
- PropertyRule matchedRule = findMatchRule(pathOfComponentInstances, i, rules);
- log.trace("Match rule is {}", matchedRule);
+ public void updateRulesInPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty,
+ String resourceInstanceId) {
+ List<PropertyRule> currentRules = propertyValueData.getRules();
+ List<PropertyRule> rules = resourceInstanceProperty.getRules();
+ // if rules are not supported.
+ if (rules == null) {
+ PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
+ rules = new ArrayList<>();
+ rules.add(propertyRule);
+ if (currentRules != null) {
+ rules = mergeRules(currentRules, rules);
+ }
+ } else {
+ // Full mode. all rules are sent in update operation.
+ rules = sortRules(rules);
+ }
+ propertyValueData.setRules(rules);
+ }
- if (matchedRule != null) {
- result = matchedRule.getValue();
- break;
- }
+ private List<PropertyRule> mergeRules(List<PropertyRule> currentRules, List<PropertyRule> newRules) {
+ List<PropertyRule> mergedRules = new ArrayList<>();
+ if (newRules == null || newRules.isEmpty()) {
+ return currentRules;
+ }
+ for (PropertyRule rule : currentRules) {
+ PropertyRule propertyRule = new PropertyRule(rule.getRule(), rule.getValue());
+ mergedRules.add(propertyRule);
+ }
+ for (PropertyRule rule : newRules) {
+ PropertyRule foundRule = findRuleInList(rule, mergedRules);
+ if (foundRule != null) {
+ foundRule.setValue(rule.getValue());
+ } else {
+ mergedRules.add(rule);
+ }
+ }
+ return mergedRules;
+ }
- }
+ private PropertyRule findRuleInList(PropertyRule rule, List<PropertyRule> rules) {
+ if (rules == null || rules.isEmpty() || rule.getRule() == null || rule.getRule().isEmpty()) {
+ return null;
+ }
+ PropertyRule foundRule = null;
+ for (PropertyRule propertyRule : rules) {
+ if (rule.getRuleSize() != propertyRule.getRuleSize()) {
+ continue;
+ }
+ boolean equals = propertyRule.compareRule(rule);
+ if (equals) {
+ foundRule = propertyRule;
+ break;
+ }
+ }
+ return foundRule;
+ }
- return Either.left(result);
+ /**
+ * return all properties associated to resource instance. The result does contains the property unique id but not its type, default value...
+ *
+ * @param resourceInstanceUid
+ * @return
+ */
+ public Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(
+ String resourceInstanceUid) {
+ return getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceUid, NodeTypeEnum.ResourceInstance);
+ }
- }
+ public Either<PropertyValueData, JanusGraphOperationStatus> removePropertyOfResourceInstance(String propertyValueUid, String resourceInstanceId) {
+ Either<ComponentInstanceData, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class);
+ if (findResInstanceRes.isRight()) {
+ JanusGraphOperationStatus status = findResInstanceRes.right().value();
+ if (status == JanusGraphOperationStatus.NOT_FOUND) {
+ status = JanusGraphOperationStatus.INVALID_ID;
+ }
+ return Either.right(status);
+ }
+ Either<PropertyValueData, JanusGraphOperationStatus> findPropertyDefRes = janusGraphGenericDao
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, PropertyValueData.class);
+ if (findPropertyDefRes.isRight()) {
+ JanusGraphOperationStatus status = findPropertyDefRes.right().value();
+ if (status == JanusGraphOperationStatus.NOT_FOUND) {
+ status = JanusGraphOperationStatus.INVALID_ID;
+ }
+ return Either.right(status);
+ }
+ Either<GraphRelation, JanusGraphOperationStatus> relation = janusGraphGenericDao
+ .getRelation(findResInstanceRes.left().value(), findPropertyDefRes.left().value(), GraphEdgeLabels.PROPERTY_VALUE);
+ if (relation.isRight()) {
+ // TODO: add error in case of error
+ JanusGraphOperationStatus status = relation.right().value();
+ if (status == JanusGraphOperationStatus.NOT_FOUND) {
+ status = JanusGraphOperationStatus.INVALID_ID;
+ }
+ return Either.right(status);
+ }
+ Either<PropertyValueData, JanusGraphOperationStatus> deleteNode = janusGraphGenericDao
+ .deleteNode(findPropertyDefRes.left().value(), PropertyValueData.class);
+ if (deleteNode.isRight()) {
+ return Either.right(deleteNode.right().value());
+ }
+ PropertyValueData value = deleteNode.left().value();
+ return Either.left(value);
+ }
- private ComponentInstanceProperty fetchByPropertyUid(List<ComponentInstanceProperty> list, String propertyUniqueId) {
+ public Either<ComponentInstanceProperty, StorageOperationStatus> removePropertyValueFromResourceInstance(String propertyValueUid,
+ String resourceInstanceId,
+ boolean inTransaction) {
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
+ try {
+ Either<PropertyValueData, JanusGraphOperationStatus> eitherStatus = this
+ .removePropertyOfResourceInstance(propertyValueUid, resourceInstanceId);
+ if (eitherStatus.isRight()) {
+ log.error("Failed to remove property value {} from resource instance {} in Graph. status is {}", propertyValueUid, resourceInstanceId,
+ eitherStatus.right().value().name());
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
+ return result;
+ } else {
+ PropertyValueData propertyValueData = eitherStatus.left().value();
+ ComponentInstanceProperty propertyValueResult = new ComponentInstanceProperty();
+ propertyValueResult.setUniqueId(resourceInstanceId);
+ propertyValueResult.setValue(propertyValueData.getValue());
+ log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
+ result = Either.left(propertyValueResult);
+ return result;
+ }
+ } finally {
+ if (!inTransaction) {
+ if (result == null || result.isRight()) {
+ log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
+ janusGraphGenericDao.rollback();
+ } else {
+ log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
+ janusGraphGenericDao.commit();
+ }
+ }
+ }
+ }
- ComponentInstanceProperty result = null;
+ public ComponentInstanceProperty buildResourceInstanceProperty(PropertyValueData propertyValueData,
+ ComponentInstanceProperty resourceInstanceProperty) {
+ String value = propertyValueData.getValue();
+ String uid = propertyValueData.getUniqueId();
+ ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(resourceInstanceProperty, value, uid);
+ instanceProperty.setPath(resourceInstanceProperty.getPath());
+ return instanceProperty;
+ }
- if (list == null) {
- return null;
- }
+ @Override
+ public boolean isPropertyDefaultValueValid(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
+ if (propertyDefinition == null) {
+ return false;
+ }
+ String innerType = null;
+ String propertyType = propertyDefinition.getType();
+ ToscaPropertyType type = getType(propertyType);
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = propertyDefinition.getSchema();
+ if (def == null) {
+ return false;
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ return false;
+ }
+ innerType = propDef.getType();
+ }
+ String value = propertyDefinition.getDefaultValue();
+ if (type != null) {
+ return isValidValue(type, value, innerType, dataTypes);
+ } else {
+ log.trace("The given type {} is not a pre defined one.", propertyType);
+ DataTypeDefinition foundDt = dataTypes.get(propertyType);
+ if (foundDt != null) {
+ return isValidComplexValue(foundDt, value, dataTypes);
+ } else {
+ return false;
+ }
+ }
+ }
- for (ComponentInstanceProperty instProperty : list) {
- if (instProperty.getUniqueId().equals(propertyUniqueId)) {
- result = instProperty;
- break;
- }
- }
+ public boolean isPropertyTypeValid(IComplexDefaultValue property) {
+ if (property == null) {
+ return false;
+ }
+ if (ToscaPropertyType.isValidType(property.getType()) == null) {
+ Either<Boolean, JanusGraphOperationStatus> definedInDataTypes = isDefinedInDataTypes(property.getType());
+ if (definedInDataTypes.isRight()) {
+ return false;
+ } else {
+ Boolean isExist = definedInDataTypes.left().value();
+ return isExist.booleanValue();
+ }
+ }
+ return true;
+ }
- return result;
- }
+ @Override
+ public ImmutablePair<String, Boolean> isPropertyInnerTypeValid(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
+ if (property == null) {
+ return new ImmutablePair<>(null, false);
+ }
+ SchemaDefinition schema;
+ PropertyDataDefinition innerProp;
+ String innerType = null;
+ if ((schema = property.getSchema()) != null) {
+ if ((innerProp = schema.getProperty()) != null) {
+ innerType = innerProp.getType();
+ }
+ }
+ ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
+ if (innerToscaType == null) {
+ DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
+ if (dataTypeDefinition == null) {
+ log.debug("The inner type {} is not a data type.", innerType);
+ return new ImmutablePair<>(innerType, false);
+ } else {
+ log.debug("The inner type {} is a data type. Data type definition is {}", innerType, dataTypeDefinition);
+ }
+ }
+ return new ImmutablePair<>(innerType, true);
+ }
- private List<PropertyRule> getOrBuildRulesIfNotExists(int ruleSize, String compInstanceId, List<PropertyRule> rules, String value) {
+ private boolean isValidComplexValue(DataTypeDefinition foundDt, String value, Map<String, DataTypeDefinition> dataTypes) {
+ ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter.validateAndUpdate(value, foundDt, dataTypes);
+ log.trace("The result after validating complex value of type {} is {}", foundDt.getName(), validateAndUpdate);
+ return validateAndUpdate.right.booleanValue();
+ }
- if (rules != null) {
- return rules;
- }
+ public Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(
+ String resourceInstanceUid, NodeTypeEnum instanceNodeType) {
+ Either<JanusGraphVertex, JanusGraphOperationStatus> findResInstanceRes = janusGraphGenericDao
+ .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid);
+ if (findResInstanceRes.isRight()) {
+ JanusGraphOperationStatus status = findResInstanceRes.right().value();
+ if (status == JanusGraphOperationStatus.NOT_FOUND) {
+ status = JanusGraphOperationStatus.INVALID_ID;
+ }
+ return Either.right(status);
+ }
+ Either<List<ImmutablePair<JanusGraphVertex, Edge>>, JanusGraphOperationStatus> propertyImplNodes = janusGraphGenericDao
+ .getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.PROPERTY_VALUE);
+ if (propertyImplNodes.isRight()) {
+ JanusGraphOperationStatus status = propertyImplNodes.right().value();
+ return Either.right(status);
+ }
+ List<ImmutablePair<JanusGraphVertex, Edge>> list = propertyImplNodes.left().value();
+ if (list == null || list.isEmpty()) {
+ return Either.right(JanusGraphOperationStatus.NOT_FOUND);
+ }
+ List<ComponentInstanceProperty> result = new ArrayList<>();
+ for (ImmutablePair<JanusGraphVertex, Edge> propertyValue : list) {
+ JanusGraphVertex propertyValueDataVertex = propertyValue.getLeft();
+ String propertyValueUid = (String) janusGraphGenericDao
+ .getProperty(propertyValueDataVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ String value = (String) janusGraphGenericDao.getProperty(propertyValueDataVertex, GraphPropertiesDictionary.VALUE.getProperty());
+ ImmutablePair<JanusGraphVertex, Edge> propertyDefPair = janusGraphGenericDao
+ .getChildVertex(propertyValueDataVertex, GraphEdgeLabels.PROPERTY_IMPL);
+ if (propertyDefPair == null) {
+ return Either.right(JanusGraphOperationStatus.NOT_FOUND);
+ }
+ Map<String, Object> properties = janusGraphGenericDao.getProperties(propertyValueDataVertex);
+ PropertyValueData propertyValueData = GraphElementFactory
+ .createElement(NodeTypeEnum.PropertyValue.getName(), GraphElementTypeEnum.Node, properties, PropertyValueData.class);
+ String propertyUniqueId = (String) janusGraphGenericDao
+ .getProperty(propertyDefPair.left, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty();
+ // set property original unique id
+ resourceInstanceProperty.setUniqueId(propertyUniqueId);
+ // set resource id
+
+ // TODO: esofer add resource id
+ resourceInstanceProperty.setParentUniqueId(null);
+ // set value
+ resourceInstanceProperty.setValue(value);
+ // set property value unique id
+ resourceInstanceProperty.setValueUniqueUid(propertyValueUid);
+ // set rules
+ resourceInstanceProperty.setRules(propertyValueData.getRules());
+ result.add(resourceInstanceProperty);
+ }
+ return Either.left(result);
+ }
- rules = buildDefaultRule(compInstanceId, ruleSize, value);
+ /**
+ * Find the default value from the list of component instances. Start the search from the second component instance
+ *
+ * @param pathOfComponentInstances
+ * @param propertyUniqueId
+ * @param defaultValue
+ * @return
+ */
+ public Either<String, JanusGraphOperationStatus> findDefaultValueFromSecondPosition(List<String> pathOfComponentInstances,
+ String propertyUniqueId, String defaultValue) {
+ log.trace("In find default value: path= {} propertyUniqId={} defaultValue= {}", pathOfComponentInstances, propertyUniqueId, defaultValue);
+ if (pathOfComponentInstances == null || pathOfComponentInstances.size() < 2) {
+ return Either.left(defaultValue);
+ }
+ String result = defaultValue;
+ for (int i = 1; i < pathOfComponentInstances.size(); i++) {
+ String compInstanceId = pathOfComponentInstances.get(i);
+ Either<List<ComponentInstanceProperty>, JanusGraphOperationStatus> propertyValuesResult = this
+ .getAllPropertiesOfResourceInstanceOnlyPropertyDefId(compInstanceId, NodeTypeEnum.ResourceInstance);
+ log.trace("After fetching properties values of component instance {}. {}", compInstanceId, propertyValuesResult);
+ if (propertyValuesResult.isRight()) {
+ JanusGraphOperationStatus status = propertyValuesResult.right().value();
+ if (status != JanusGraphOperationStatus.NOT_FOUND) {
+ return Either.right(status);
+ } else {
+ continue;
+ }
+ }
+ ComponentInstanceProperty foundCompInstanceProperty = fetchByPropertyUid(propertyValuesResult.left().value(), propertyUniqueId);
+ log.trace("After finding the component instance property on{} . {}", compInstanceId, foundCompInstanceProperty);
+ if (foundCompInstanceProperty == null) {
+ continue;
+ }
+ List<PropertyRule> rules = getOrBuildRulesIfNotExists(pathOfComponentInstances.size() - i, pathOfComponentInstances.get(i),
+ foundCompInstanceProperty.getRules(), foundCompInstanceProperty.getValue());
+ log.trace("Rules of property {} on component instance {} are {}", propertyUniqueId, compInstanceId, rules);
+ PropertyRule matchedRule = findMatchRule(pathOfComponentInstances, i, rules);
+ log.trace("Match rule is {}", matchedRule);
+ if (matchedRule != null) {
+ result = matchedRule.getValue();
+ break;
+ }
+ }
+ return Either.left(result);
+ }
- return rules;
+ private ComponentInstanceProperty fetchByPropertyUid(List<ComponentInstanceProperty> list, String propertyUniqueId) {
+ ComponentInstanceProperty result = null;
+ if (list == null) {
+ return null;
+ }
+ for (ComponentInstanceProperty instProperty : list) {
+ if (instProperty.getUniqueId().equals(propertyUniqueId)) {
+ result = instProperty;
+ break;
+ }
+ }
+ return result;
+ }
- }
+ private List<PropertyRule> getOrBuildRulesIfNotExists(int ruleSize, String compInstanceId, List<PropertyRule> rules, String value) {
+ if (rules != null) {
+ return rules;
+ }
+ rules = buildDefaultRule(compInstanceId, ruleSize, value);
+ return rules;
+ }
- private List<PropertyRule> getRulesOfPropertyValue(int size, String instanceId, ComponentInstanceProperty componentInstanceProperty) {
- List<PropertyRule> rules = componentInstanceProperty.getRules();
- if (rules == null) {
- rules = buildDefaultRule(instanceId, size, componentInstanceProperty.getValue());
- }
- return rules;
- }
+ private List<PropertyRule> getRulesOfPropertyValue(int size, String instanceId, ComponentInstanceProperty componentInstanceProperty) {
+ List<PropertyRule> rules = componentInstanceProperty.getRules();
+ if (rules == null) {
+ rules = buildDefaultRule(instanceId, size, componentInstanceProperty.getValue());
+ }
+ return rules;
+ }
- private List<PropertyRule> buildDefaultRule(String componentInstanceId, int size, String value) {
+ private List<PropertyRule> buildDefaultRule(String componentInstanceId, int size, String value) {
+ List<PropertyRule> rules = new ArrayList<>();
+ List<String> rule = new ArrayList<>();
+ rule.add(componentInstanceId);
+ for (int i = 0; i < size - 1; i++) {
+ rule.add(PropertyRule.getRuleAnyMatch());
+ }
+ PropertyRule propertyRule = new PropertyRule(rule, value);
+ rules.add(propertyRule);
+ return rules;
+ }
- List<PropertyRule> rules = new ArrayList<>();
- List<String> rule = new ArrayList<>();
- rule.add(componentInstanceId);
- for (int i = 0; i < size - 1; i++) {
- rule.add(PropertyRule.getRuleAnyMatch());
- }
- PropertyRule propertyRule = new PropertyRule(rule, value);
- rules.add(propertyRule);
+ private PropertyRule findMatchRule(List<String> pathOfInstances, int level, List<PropertyRule> rules) {
+ PropertyRule propertyRule = null;
+ String stringForMatch = buildStringForMatch(pathOfInstances, level);
+ String firstCompInstance = pathOfInstances.get(level);
+ if (rules != null) {
+ for (PropertyRule rule : rules) {
+ int ruleSize = rule.getRule().size();
+ // check the length of the rule equals to the length of the
+
+ // instances path.
+ if (ruleSize != pathOfInstances.size() - level) {
+ continue;
+ }
+ // check that the rule starts with correct component instance id
+ if (!checkFirstItem(firstCompInstance, rule.getFirstToken())) {
+ continue;
+ }
+ String secondToken = rule.getToken(2);
+ if (secondToken != null && (secondToken.equals(PropertyRule.getForceAll()) || secondToken.equals(PropertyRule.getALL()))) {
+ propertyRule = rule;
+ break;
+ }
+ String patternStr = buildStringForMatch(rule.getRule(), 0);
+ Pattern pattern = Pattern.compile(patternStr);
+ Matcher matcher = pattern.matcher(stringForMatch);
+ if (matcher.matches()) {
+ if (log.isTraceEnabled()) {
+ log.trace("{} matches the rule {}", stringForMatch, patternStr);
+ }
+ propertyRule = rule;
+ break;
+ }
+ }
+ }
+ return propertyRule;
+ }
- return rules;
+ private boolean checkFirstItem(String left, String right) {
+ if (left != null && left.equals(right)) {
+ return true;
+ }
+ return false;
+ }
- }
+ private String buildStringForMatch(List<String> pathOfInstances, int level) {
+ StringBuilder builder = new StringBuilder();
+ for (int i = level; i < pathOfInstances.size(); i++) {
+ builder.append(pathOfInstances.get(i));
+ if (i < pathOfInstances.size() - 1) {
+ builder.append("#");
+ }
+ }
+ return builder.toString();
+ }
- private PropertyRule findMatchRule(List<String> pathOfInstances, int level, List<PropertyRule> rules) {
+ public void updatePropertyByBestMatch(String propertyUniqueId, ComponentInstanceProperty instanceProperty,
+ Map<String, ComponentInstanceProperty> instanceIdToValue) {
+ List<String> pathOfInstances = instanceProperty.getPath();
+ int level = 0;
+ int size = pathOfInstances.size();
+ int numberOfMatches = 0;
+ for (String instanceId : pathOfInstances) {
+ ComponentInstanceProperty componentInstanceProperty = instanceIdToValue.get(instanceId);
+ if (componentInstanceProperty != null) {
+ List<PropertyRule> rules = getRulesOfPropertyValue(size - level, instanceId, componentInstanceProperty);
+ // If it is the first level instance, then update valueUniuqeId
+
+ // parameter in order to know on update that
+
+ // we should update and not create new node on graph.
+ if (level == 0) {
+ instanceProperty.setValueUniqueUid(componentInstanceProperty.getValueUniqueUid());
+ instanceProperty.setRules(rules);
+ }
+ PropertyRule rule = findMatchRule(pathOfInstances, level, rules);
+ if (rule != null) {
+ numberOfMatches++;
+ String value = rule.getValue();
+ if (numberOfMatches == 1) {
+ instanceProperty.setValue(value);
+ if (log.isDebugEnabled()) {
+ log.debug("Set the value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(),
+ pathOfInstances, value);
+ }
+ } else if (numberOfMatches == 2) {
+ // In case of another property value match, then use the
+
+ // value to be the default value of the property.
+ instanceProperty.setDefaultValue(value);
+ if (log.isDebugEnabled()) {
+ log.debug("Set the default value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(),
+ pathOfInstances, value);
+ }
+ break;
+ }
+ }
+ }
+ level++;
+ }
+ }
- PropertyRule propertyRule = null;
+ /**
+ * Add data type to graph.
+ * <p>
+ * 1. Add data type node
+ * <p>
+ * 2. Add edge between the former node to its parent(if exists)
+ * <p>
+ * 3. Add property node and associate it to the node created at #1. (per property & if exists)
+ *
+ * @param dataTypeDefinition
+ * @return
+ */
+ private Either<DataTypeData, JanusGraphOperationStatus> addDataTypeToGraph(DataTypeDefinition dataTypeDefinition) {
+ log.debug("Got data type {}", dataTypeDefinition);
+ String dtUniqueId = UniqueIdBuilder.buildDataTypeUid(dataTypeDefinition.getName());
+ DataTypeData dataTypeData = buildDataTypeData(dataTypeDefinition, dtUniqueId);
+ log.debug("Before adding data type to graph. dataTypeData = {}", dataTypeData);
+ Either<DataTypeData, JanusGraphOperationStatus> createDataTypeResult = janusGraphGenericDao.createNode(dataTypeData, DataTypeData.class);
+ log.debug("After adding data type to graph. status is = {}", createDataTypeResult);
+ if (createDataTypeResult.isRight()) {
+ JanusGraphOperationStatus operationStatus = createDataTypeResult.right().value();
+ log.debug("Failed to data type {} to graph. status is {}", dataTypeDefinition.getName(), operationStatus);
+ BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", NodeTypeEnum.DataType.getName());
+ return Either.right(operationStatus);
+ }
+ DataTypeData resultCTD = createDataTypeResult.left().value();
+ List<PropertyDefinition> properties = dataTypeDefinition.getProperties();
+ Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType = addPropertiesToDataType(resultCTD.getUniqueId(),
+ properties);
+ if (addPropertiesToDataType.isRight()) {
+ log.debug("Failed add properties {} to data type {}", properties, dataTypeDefinition.getName());
+ return Either.right(addPropertiesToDataType.right().value());
+ }
+ String derivedFrom = dataTypeDefinition.getDerivedFromName();
+ if (derivedFrom != null) {
+ log.debug("Before creating relation between data type {} to its parent {}", dtUniqueId, derivedFrom);
+ UniqueIdData from = new UniqueIdData(NodeTypeEnum.DataType, dtUniqueId);
+ String deriveFromUid = UniqueIdBuilder.buildDataTypeUid(derivedFrom);
+ UniqueIdData to = new UniqueIdData(NodeTypeEnum.DataType, deriveFromUid);
+ Either<GraphRelation, JanusGraphOperationStatus> createRelation = janusGraphGenericDao
+ .createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null);
+ log.debug("After create relation between capability type {} to its parent {}. status is {}", dtUniqueId, derivedFrom, createRelation);
+ if (createRelation.isRight()) {
+ return Either.right(createRelation.right().value());
+ }
+ }
+ return Either.left(createDataTypeResult.left().value());
+ }
- String stringForMatch = buildStringForMatch(pathOfInstances, level);
-
- String firstCompInstance = pathOfInstances.get(level);
-
- if (rules != null) {
-
- for (PropertyRule rule : rules) {
-
- int ruleSize = rule.getRule().size();
- // check the length of the rule equals to the length of the
- // instances path.
- if (ruleSize != pathOfInstances.size() - level) {
- continue;
- }
- // check that the rule starts with correct component instance id
- if (!checkFirstItem(firstCompInstance, rule.getFirstToken())) {
- continue;
- }
-
- String secondToken = rule.getToken(2);
- if (secondToken != null && (secondToken.equals(PropertyRule.getForceAll()) || secondToken.equals(PropertyRule.getALL()))) {
- propertyRule = rule;
- break;
- }
-
- String patternStr = buildStringForMatch(rule.getRule(), 0);
-
- Pattern pattern = Pattern.compile(patternStr);
-
- Matcher matcher = pattern.matcher(stringForMatch);
-
- if (matcher.matches()) {
- if (log.isTraceEnabled()) {
- log.trace("{} matches the rule {}", stringForMatch, patternStr);
- }
- propertyRule = rule;
- break;
- }
- }
-
- }
-
- return propertyRule;
- }
-
- private boolean checkFirstItem(String left, String right) {
- if (left != null && left.equals(right)) {
- return true;
- }
- return false;
- }
-
- private String buildStringForMatch(List<String> pathOfInstances, int level) {
- StringBuilder builder = new StringBuilder();
-
- for (int i = level; i < pathOfInstances.size(); i++) {
- builder.append(pathOfInstances.get(i));
- if (i < pathOfInstances.size() - 1) {
- builder.append("#");
- }
- }
- return builder.toString();
- }
-
- public void updatePropertyByBestMatch(String propertyUniqueId, ComponentInstanceProperty instanceProperty, Map<String, ComponentInstanceProperty> instanceIdToValue) {
-
- List<String> pathOfInstances = instanceProperty.getPath();
- int level = 0;
- int size = pathOfInstances.size();
- int numberOfMatches = 0;
- for (String instanceId : pathOfInstances) {
- ComponentInstanceProperty componentInstanceProperty = instanceIdToValue.get(instanceId);
-
- if (componentInstanceProperty != null) {
-
- List<PropertyRule> rules = getRulesOfPropertyValue(size - level, instanceId, componentInstanceProperty);
- // If it is the first level instance, then update valueUniuqeId
- // parameter in order to know on update that
- // we should update and not create new node on graph.
- if (level == 0) {
- instanceProperty.setValueUniqueUid(componentInstanceProperty.getValueUniqueUid());
- instanceProperty.setRules(rules);
- }
-
- PropertyRule rule = findMatchRule(pathOfInstances, level, rules);
- if (rule != null) {
- numberOfMatches++;
- String value = rule.getValue();
- if (numberOfMatches == 1) {
- instanceProperty.setValue(value);
- if (log.isDebugEnabled()) {
- log.debug("Set the value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(), pathOfInstances, value);
- }
- } else if (numberOfMatches == 2) {
- // In case of another property value match, then use the
- // value to be the default value of the property.
- instanceProperty.setDefaultValue(value);
- if (log.isDebugEnabled()) {
- log.debug("Set the default value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(), pathOfInstances, value);
- }
- break;
- }
- }
- }
- level++;
- }
-
- }
-
- /**
- *
- * Add data type to graph.
- *
- * 1. Add data type node
- *
- * 2. Add edge between the former node to its parent(if exists)
- *
- * 3. Add property node and associate it to the node created at #1. (per property & if exists)
- *
- * @param dataTypeDefinition
- * @return
- */
- private Either<DataTypeData, JanusGraphOperationStatus> addDataTypeToGraph(DataTypeDefinition dataTypeDefinition) {
-
- log.debug("Got data type {}", dataTypeDefinition);
-
- String dtUniqueId = UniqueIdBuilder.buildDataTypeUid(dataTypeDefinition.getName());
-
- DataTypeData dataTypeData = buildDataTypeData(dataTypeDefinition, dtUniqueId);
-
- log.debug("Before adding data type to graph. dataTypeData = {}", dataTypeData);
- Either<DataTypeData, JanusGraphOperationStatus> createDataTypeResult = janusGraphGenericDao
- .createNode(dataTypeData, DataTypeData.class);
- log.debug("After adding data type to graph. status is = {}", createDataTypeResult);
-
- if (createDataTypeResult.isRight()) {
- JanusGraphOperationStatus operationStatus = createDataTypeResult.right().value();
- log.debug("Failed to data type {} to graph. status is {}", dataTypeDefinition.getName(), operationStatus);
- BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", NodeTypeEnum.DataType.getName());
- return Either.right(operationStatus);
- }
-
- DataTypeData resultCTD = createDataTypeResult.left().value();
- List<PropertyDefinition> properties = dataTypeDefinition.getProperties();
- Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType = addPropertiesToDataType(resultCTD.getUniqueId(), properties);
- if (addPropertiesToDataType.isRight()) {
- log.debug("Failed add properties {} to data type {}", properties, dataTypeDefinition.getName());
- return Either.right(addPropertiesToDataType.right().value());
- }
-
- String derivedFrom = dataTypeDefinition.getDerivedFromName();
- if (derivedFrom != null) {
- log.debug("Before creating relation between data type {} to its parent {}", dtUniqueId, derivedFrom);
- UniqueIdData from = new UniqueIdData(NodeTypeEnum.DataType, dtUniqueId);
-
- String deriveFromUid = UniqueIdBuilder.buildDataTypeUid(derivedFrom);
- UniqueIdData to = new UniqueIdData(NodeTypeEnum.DataType, deriveFromUid);
- Either<GraphRelation, JanusGraphOperationStatus> createRelation = janusGraphGenericDao
- .createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null);
- log.debug("After create relation between capability type {} to its parent {}. status is {}", dtUniqueId, derivedFrom, createRelation);
- if (createRelation.isRight()) {
- return Either.right(createRelation.right().value());
- }
- }
-
- return Either.left(createDataTypeResult.left().value());
-
- }
-
- private DataTypeData buildDataTypeData(DataTypeDefinition dataTypeDefinition, String ctUniqueId) {
-
- DataTypeData dataTypeData = new DataTypeData(dataTypeDefinition);
-
- dataTypeData.getDataTypeDataDefinition().setUniqueId(ctUniqueId);
- Long creationDate = dataTypeData.getDataTypeDataDefinition().getCreationTime();
- if (creationDate == null) {
- creationDate = System.currentTimeMillis();
- }
- dataTypeData.getDataTypeDataDefinition().setCreationTime(creationDate);
- dataTypeData.getDataTypeDataDefinition().setModificationTime(creationDate);
-
- return dataTypeData;
- }
-
- /**
- * add properties to capability type.
- *
- * Per property, add a property node and associate it to the capability type
- *
- * @param uniqueId
- * @param properties
- * @return
- */
- private Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType(String uniqueId, List<PropertyDefinition> properties) {
-
- Map<String, PropertyData> propertiesData = new HashMap<>();
-
- if (properties != null && !properties.isEmpty()) {
- for (PropertyDefinition propertyDefinition : properties) {
- String propertyName = propertyDefinition.getName();
-
- String propertyType = propertyDefinition.getType();
- Either<Boolean, JanusGraphOperationStatus> validPropertyType = isValidPropertyType(propertyType);
- if (validPropertyType.isRight()) {
- log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType);
- return Either.right(validPropertyType.right().value());
- }
- Boolean isValid = validPropertyType.left().value();
- if (isValid == null || !isValid.booleanValue()) {
- log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType);
- return Either.right(JanusGraphOperationStatus.INVALID_TYPE);
- }
-
- Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType = this.addPropertyToNodeType(propertyName, propertyDefinition, NodeTypeEnum.DataType, uniqueId);
- if (addPropertyToNodeType.isRight()) {
- JanusGraphOperationStatus operationStatus = addPropertyToNodeType.right().value();
- log.debug("Failed to associate data type {} to property {} in graph. status is {}", uniqueId, propertyName, operationStatus);
- BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToDataType", "Failed to associate property to data type. Status is " + operationStatus, ErrorSeverity.ERROR);
- return Either.right(operationStatus);
- }
- propertiesData.put(propertyName, addPropertyToNodeType.left().value());
- }
-
- DataTypeData dataTypeData = new DataTypeData();
- dataTypeData.getDataTypeDataDefinition().setUniqueId(uniqueId);
- long modificationTime = System.currentTimeMillis();
- dataTypeData.getDataTypeDataDefinition().setModificationTime(modificationTime);
-
- Either<DataTypeData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao
- .updateNode(dataTypeData, DataTypeData.class);
- if (updateNode.isRight()) {
- JanusGraphOperationStatus operationStatus = updateNode.right().value();
- log.debug("Failed to update modification time data type {} from graph. status is {}", uniqueId, operationStatus);
- BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToDataType", "Failed to fetch data type. Status is " + operationStatus, ErrorSeverity.ERROR);
- return Either.right(operationStatus);
- } else {
- log.debug("Update data type uid {}. Set modification time to {}", uniqueId, modificationTime);
- }
-
- }
-
- return Either.left(propertiesData);
-
- }
-
- /**
- * Build Data type object from graph by unique id
- *
- * @param uniqueId
- * @return
- */
- public Either<DataTypeDefinition, JanusGraphOperationStatus> getDataTypeByUid(String uniqueId) {
-
- Either<DataTypeDefinition, JanusGraphOperationStatus> result = null;
-
- Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
-
- if (dataTypesRes.isRight()) {
- JanusGraphOperationStatus status = dataTypesRes.right().value();
- log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
- return Either.right(status);
- }
-
- DataTypeData ctData = dataTypesRes.left().value();
- DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
-
- JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
- if (propertiesStatus != JanusGraphOperationStatus.OK) {
- log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
- return Either.right(propertiesStatus);
- }
-
- Either<ImmutablePair<DataTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
- DataTypeData.class);
- log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode);
- if (parentNode.isRight()) {
- JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
- if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
- log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId,
- janusGraphOperationStatus);
- result = Either.right(janusGraphOperationStatus);
- return result;
- }
- } else {
- // derived from node was found
- ImmutablePair<DataTypeData, GraphEdge> immutablePair = parentNode.left().value();
- DataTypeData parentCT = immutablePair.getKey();
-
- String parentUniqueId = parentCT.getUniqueId();
- Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(parentUniqueId);
-
- if (dataTypeByUid.isRight()) {
- return Either.right(dataTypeByUid.right().value());
- }
-
- DataTypeDefinition parentDataTypeDefinition = dataTypeByUid.left().value();
-
- dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
-
- }
- result = Either.left(dataTypeDefinition);
-
- return result;
- }
-
- private JanusGraphOperationStatus fillProperties(String uniqueId, DataTypeDefinition dataTypeDefinition) {
-
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(NodeTypeEnum.DataType, uniqueId);
- if (findPropertiesOfNode.isRight()) {
- JanusGraphOperationStatus janusGraphOperationStatus = findPropertiesOfNode.right().value();
- log.debug("After looking for properties of vertex {}. status is {}", uniqueId,
- janusGraphOperationStatus);
- if (JanusGraphOperationStatus.NOT_FOUND.equals(janusGraphOperationStatus)) {
- return JanusGraphOperationStatus.OK;
- } else {
- return janusGraphOperationStatus;
- }
- } else {
- Map<String, PropertyDefinition> properties = findPropertiesOfNode.left().value();
- if (properties != null && !properties.isEmpty()) {
- List<PropertyDefinition> listOfProps = new ArrayList<>();
-
- for (Entry<String, PropertyDefinition> entry : properties.entrySet()) {
- String propName = entry.getKey();
- PropertyDefinition propertyDefinition = entry.getValue();
- PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition);
- newPropertyDefinition.setName(propName);
- listOfProps.add(newPropertyDefinition);
- }
- dataTypeDefinition.setProperties(listOfProps);
- }
- return JanusGraphOperationStatus.OK;
- }
- }
-
- private Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction) {
-
- Either<DataTypeDefinition, StorageOperationStatus> result = null;
-
- try {
-
- Either<DataTypeData, JanusGraphOperationStatus> eitherStatus = addDataTypeToGraph(dataTypeDefinition);
-
- if (eitherStatus.isRight()) {
- log.debug("Failed to add data type {} to Graph. status is {}", dataTypeDefinition, eitherStatus.right().value().name());
- BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", "DataType");
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
- return result;
- } else {
- DataTypeData capabilityTypeData = eitherStatus.left().value();
-
- DataTypeDefinition dataTypeDefResult = convertDTDataToDTDefinition(capabilityTypeData);
- log.debug("The returned CapabilityTypeDefinition is {}", dataTypeDefResult);
- result = Either.left(dataTypeDefResult);
- return result;
- }
- } finally {
- if (!inTransaction) {
- if (result == null || result.isRight()) {
- log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
- janusGraphGenericDao.rollback();
- } else {
- log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
- janusGraphGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition) {
- return addDataType(dataTypeDefinition, true);
- }
-
- @Override
- public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(String name, boolean inTransaction) {
-
- Either<DataTypeDefinition, StorageOperationStatus> result = null;
- try {
-
- String dtUid = UniqueIdBuilder.buildDataTypeUid(name);
- Either<DataTypeDefinition, JanusGraphOperationStatus> ctResult = this.getDataTypeByUid(dtUid);
-
- if (ctResult.isRight()) {
- JanusGraphOperationStatus status = ctResult.right().value();
- if (status != JanusGraphOperationStatus.NOT_FOUND) {
- log.error("Failed to retrieve information on capability type {} status is {}", name, status);
- }
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value()));
- return result;
- }
-
- result = Either.left(ctResult.left().value());
-
- return result;
- } finally {
- if (!inTransaction) {
- if (result == null || result.isRight()) {
- log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
- janusGraphGenericDao.rollback();
- } else {
- log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
- janusGraphGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(String name) {
- return getDataTypeByName(name, true);
- }
-
- @Override
- public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name) {
- return getDataTypeByNameWithoutDerived(name, true);
- }
-
- private Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name, boolean inTransaction) {
-
- Either<DataTypeDefinition, StorageOperationStatus> result = null;
- try {
-
- String uid = UniqueIdBuilder.buildDataTypeUid(name);
- Either<DataTypeDefinition, JanusGraphOperationStatus> ctResult = this.getDataTypeByUidWithoutDerivedDataTypes(uid);
-
- if (ctResult.isRight()) {
- JanusGraphOperationStatus status = ctResult.right().value();
- if (status != JanusGraphOperationStatus.NOT_FOUND) {
- log.error("Failed to retrieve information on capability type {} status is {}", name, status);
- }
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value()));
- return result;
- }
-
- result = Either.left(ctResult.left().value());
-
- return result;
- } finally {
- if (!inTransaction) {
- if (result == null || result.isRight()) {
- log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
- janusGraphGenericDao.rollback();
- } else {
- log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
- janusGraphGenericDao.commit();
- }
- }
- }
-
- }
-
- public Either<DataTypeDefinition, JanusGraphOperationStatus> getDataTypeByUidWithoutDerivedDataTypes(String uniqueId) {
-
- Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
-
- if (dataTypesRes.isRight()) {
- JanusGraphOperationStatus status = dataTypesRes.right().value();
- log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
- return Either.right(status);
- }
-
- DataTypeData ctData = dataTypesRes.left().value();
- DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
-
- JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
- if (propertiesStatus != JanusGraphOperationStatus.OK) {
- log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
- return Either.right(propertiesStatus);
- }
-
- return Either.left(dataTypeDefinition);
- }
-
- /**
- *
- * convert between graph Node object to Java object
- *
- * @param dataTypeData
- * @return
- */
- protected DataTypeDefinition convertDTDataToDTDefinition(DataTypeData dataTypeData) {
- log.debug("The object returned after create data type is {}", dataTypeData);
+ private DataTypeData buildDataTypeData(DataTypeDefinition dataTypeDefinition, String ctUniqueId) {
+ DataTypeData dataTypeData = new DataTypeData(dataTypeDefinition);
+ dataTypeData.getDataTypeDataDefinition().setUniqueId(ctUniqueId);
+ Long creationDate = dataTypeData.getDataTypeDataDefinition().getCreationTime();
+ if (creationDate == null) {
+ creationDate = System.currentTimeMillis();
+ }
+ dataTypeData.getDataTypeDataDefinition().setCreationTime(creationDate);
+ dataTypeData.getDataTypeDataDefinition().setModificationTime(creationDate);
+ return dataTypeData;
+ }
- return new DataTypeDefinition(dataTypeData.getDataTypeDataDefinition());
- }
+ /**
+ * add properties to capability type.
+ * <p>
+ * Per property, add a property node and associate it to the capability type
+ *
+ * @param uniqueId
+ * @param properties
+ * @return
+ */
+ private Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType(String uniqueId,
+ List<PropertyDefinition> properties) {
+ Map<String, PropertyData> propertiesData = new HashMap<>();
+ if (properties != null && !properties.isEmpty()) {
+ for (PropertyDefinition propertyDefinition : properties) {
+ String propertyName = propertyDefinition.getName();
+ String propertyType = propertyDefinition.getType();
+ Either<Boolean, JanusGraphOperationStatus> validPropertyType = isValidPropertyType(propertyType);
+ if (validPropertyType.isRight()) {
+ log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType);
+ return Either.right(validPropertyType.right().value());
+ }
+ Boolean isValid = validPropertyType.left().value();
+ if (isValid == null || !isValid.booleanValue()) {
+ log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType);
+ return Either.right(JanusGraphOperationStatus.INVALID_TYPE);
+ }
+ Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType = this
+ .addPropertyToNodeType(propertyName, propertyDefinition, NodeTypeEnum.DataType, uniqueId);
+ if (addPropertyToNodeType.isRight()) {
+ JanusGraphOperationStatus operationStatus = addPropertyToNodeType.right().value();
+ log.debug("Failed to associate data type {} to property {} in graph. status is {}", uniqueId, propertyName, operationStatus);
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("AddPropertyToDataType", "Failed to associate property to data type. Status is " + operationStatus,
+ ErrorSeverity.ERROR);
+ return Either.right(operationStatus);
+ }
+ propertiesData.put(propertyName, addPropertyToNodeType.left().value());
+ }
+ DataTypeData dataTypeData = new DataTypeData();
+ dataTypeData.getDataTypeDataDefinition().setUniqueId(uniqueId);
+ long modificationTime = System.currentTimeMillis();
+ dataTypeData.getDataTypeDataDefinition().setModificationTime(modificationTime);
+ Either<DataTypeData, JanusGraphOperationStatus> updateNode = janusGraphGenericDao.updateNode(dataTypeData, DataTypeData.class);
+ if (updateNode.isRight()) {
+ JanusGraphOperationStatus operationStatus = updateNode.right().value();
+ log.debug("Failed to update modification time data type {} from graph. status is {}", uniqueId, operationStatus);
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("AddPropertyToDataType", "Failed to fetch data type. Status is " + operationStatus, ErrorSeverity.ERROR);
+ return Either.right(operationStatus);
+ } else {
+ log.debug("Update data type uid {}. Set modification time to {}", uniqueId, modificationTime);
+ }
+ }
+ return Either.left(propertiesData);
+ }
- private Either<Boolean, JanusGraphOperationStatus> isValidPropertyType(String propertyType) {
+ /**
+ * Build Data type object from graph by unique id
+ *
+ * @param uniqueId
+ * @return
+ */
+ public Either<DataTypeDefinition, JanusGraphOperationStatus> getDataTypeByUid(String uniqueId) {
+ Either<DataTypeDefinition, JanusGraphOperationStatus> result = null;
+ Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
+ if (dataTypesRes.isRight()) {
+ JanusGraphOperationStatus status = dataTypesRes.right().value();
+ log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
+ return Either.right(status);
+ }
+ DataTypeData ctData = dataTypesRes.left().value();
+ DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
+ JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
+ if (propertiesStatus != JanusGraphOperationStatus.OK) {
+ log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
+ return Either.right(propertiesStatus);
+ }
+ Either<ImmutablePair<DataTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
+ .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
+ DataTypeData.class);
+ log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode);
+ if (parentNode.isRight()) {
+ JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
+ if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
+ log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, janusGraphOperationStatus);
+ result = Either.right(janusGraphOperationStatus);
+ return result;
+ }
+ } else {
+ // derived from node was found
+ ImmutablePair<DataTypeData, GraphEdge> immutablePair = parentNode.left().value();
+ DataTypeData parentCT = immutablePair.getKey();
+ String parentUniqueId = parentCT.getUniqueId();
+ Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(parentUniqueId);
+ if (dataTypeByUid.isRight()) {
+ return Either.right(dataTypeByUid.right().value());
+ }
+ DataTypeDefinition parentDataTypeDefinition = dataTypeByUid.left().value();
+ dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
+ }
+ result = Either.left(dataTypeDefinition);
+ return result;
+ }
- if (propertyType == null || propertyType.isEmpty()) {
- return Either.left(false);
- }
+ private JanusGraphOperationStatus fillProperties(String uniqueId, DataTypeDefinition dataTypeDefinition) {
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode = this
+ .findPropertiesOfNode(NodeTypeEnum.DataType, uniqueId);
+ if (findPropertiesOfNode.isRight()) {
+ JanusGraphOperationStatus janusGraphOperationStatus = findPropertiesOfNode.right().value();
+ log.debug("After looking for properties of vertex {}. status is {}", uniqueId, janusGraphOperationStatus);
+ if (JanusGraphOperationStatus.NOT_FOUND.equals(janusGraphOperationStatus)) {
+ return JanusGraphOperationStatus.OK;
+ } else {
+ return janusGraphOperationStatus;
+ }
+ } else {
+ Map<String, PropertyDefinition> properties = findPropertiesOfNode.left().value();
+ if (properties != null && !properties.isEmpty()) {
+ List<PropertyDefinition> listOfProps = new ArrayList<>();
+ for (Entry<String, PropertyDefinition> entry : properties.entrySet()) {
+ String propName = entry.getKey();
+ PropertyDefinition propertyDefinition = entry.getValue();
+ PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition);
+ newPropertyDefinition.setName(propName);
+ listOfProps.add(newPropertyDefinition);
+ }
+ dataTypeDefinition.setProperties(listOfProps);
+ }
+ return JanusGraphOperationStatus.OK;
+ }
+ }
+
+ private Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction) {
+ Either<DataTypeDefinition, StorageOperationStatus> result = null;
+ try {
+ Either<DataTypeData, JanusGraphOperationStatus> eitherStatus = addDataTypeToGraph(dataTypeDefinition);
+ if (eitherStatus.isRight()) {
+ log.debug("Failed to add data type {} to Graph. status is {}", dataTypeDefinition, eitherStatus.right().value().name());
+ BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", "DataType");
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(eitherStatus.right().value()));
+ return result;
+ } else {
+ DataTypeData capabilityTypeData = eitherStatus.left().value();
+ DataTypeDefinition dataTypeDefResult = convertDTDataToDTDefinition(capabilityTypeData);
+ log.debug("The returned CapabilityTypeDefinition is {}", dataTypeDefResult);
+ result = Either.left(dataTypeDefResult);
+ return result;
+ }
+ } finally {
+ if (!inTransaction) {
+ if (result == null || result.isRight()) {
+ log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
+ janusGraphGenericDao.rollback();
+ } else {
+ log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
+ janusGraphGenericDao.commit();
+ }
+ }
+ }
+ }
+
+ @Override
+ public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition) {
+ return addDataType(dataTypeDefinition, true);
+ }
+
+ @Override
+ public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(String name, boolean inTransaction) {
+ Either<DataTypeDefinition, StorageOperationStatus> result = null;
+ try {
+ String dtUid = UniqueIdBuilder.buildDataTypeUid(name);
+ Either<DataTypeDefinition, JanusGraphOperationStatus> ctResult = this.getDataTypeByUid(dtUid);
+ if (ctResult.isRight()) {
+ JanusGraphOperationStatus status = ctResult.right().value();
+ if (status != JanusGraphOperationStatus.NOT_FOUND) {
+ log.error("Failed to retrieve information on capability type {} status is {}", name, status);
+ }
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value()));
+ return result;
+ }
+ result = Either.left(ctResult.left().value());
+ return result;
+ } finally {
+ if (!inTransaction) {
+ if (result == null || result.isRight()) {
+ log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
+ janusGraphGenericDao.rollback();
+ } else {
+ log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
+ janusGraphGenericDao.commit();
+ }
+ }
+ }
+ }
+
+ @Override
+ public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(String name) {
+ return getDataTypeByName(name, true);
+ }
+
+ @Override
+ public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name) {
+ return getDataTypeByNameWithoutDerived(name, true);
+ }
+
+ private Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name, boolean inTransaction) {
+ Either<DataTypeDefinition, StorageOperationStatus> result = null;
+ try {
+ String uid = UniqueIdBuilder.buildDataTypeUid(name);
+ Either<DataTypeDefinition, JanusGraphOperationStatus> ctResult = this.getDataTypeByUidWithoutDerivedDataTypes(uid);
+ if (ctResult.isRight()) {
+ JanusGraphOperationStatus status = ctResult.right().value();
+ if (status != JanusGraphOperationStatus.NOT_FOUND) {
+ log.error("Failed to retrieve information on capability type {} status is {}", name, status);
+ }
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value()));
+ return result;
+ }
+ result = Either.left(ctResult.left().value());
+ return result;
+ } finally {
+ if (!inTransaction) {
+ if (result == null || result.isRight()) {
+ log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
+ janusGraphGenericDao.rollback();
+ } else {
+ log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
+ janusGraphGenericDao.commit();
+ }
+ }
+ }
+ }
+
+ public Either<DataTypeDefinition, JanusGraphOperationStatus> getDataTypeByUidWithoutDerivedDataTypes(String uniqueId) {
+ Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
+ if (dataTypesRes.isRight()) {
+ JanusGraphOperationStatus status = dataTypesRes.right().value();
+ log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
+ return Either.right(status);
+ }
+ DataTypeData ctData = dataTypesRes.left().value();
+ DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
+ JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
+ if (propertiesStatus != JanusGraphOperationStatus.OK) {
+ log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
+ return Either.right(propertiesStatus);
+ }
+ return Either.left(dataTypeDefinition);
+ }
+
+ /**
+ * convert between graph Node object to Java object
+ *
+ * @param dataTypeData
+ * @return
+ */
+ protected DataTypeDefinition convertDTDataToDTDefinition(DataTypeData dataTypeData) {
+ log.debug("The object returned after create data type is {}", dataTypeData);
+ return new DataTypeDefinition(dataTypeData.getDataTypeDataDefinition());
+ }
- ToscaPropertyType toscaPropertyType = ToscaPropertyType.isValidType(propertyType);
- if (toscaPropertyType == null) {
+ private Either<Boolean, JanusGraphOperationStatus> isValidPropertyType(String propertyType) {
+ if (propertyType == null || propertyType.isEmpty()) {
+ return Either.left(false);
+ }
+ ToscaPropertyType toscaPropertyType = ToscaPropertyType.isValidType(propertyType);
+ if (toscaPropertyType == null) {
return isDefinedInDataTypes(propertyType);
- } else {
- return Either.left(true);
- }
- }
-
- public Either<Boolean, JanusGraphOperationStatus> isDefinedInDataTypes(String propertyType) {
-
- String dataTypeUid = UniqueIdBuilder.buildDataTypeUid(propertyType);
- Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(dataTypeUid);
- if (dataTypeByUid.isRight()) {
- JanusGraphOperationStatus status = dataTypeByUid.right().value();
- if (status == JanusGraphOperationStatus.NOT_FOUND) {
- return Either.left(false);
- }
- return Either.right(status);
- }
-
- return Either.left(true);
-
- }
-
- public Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> getAllDataTypes() {
-
- Map<String, DataTypeDefinition> dataTypes = new HashMap<>();
- Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> result = Either.left(dataTypes);
-
- Either<List<DataTypeData>, JanusGraphOperationStatus> getAllDataTypes = janusGraphGenericDao
- .getByCriteria(NodeTypeEnum.DataType, null, DataTypeData.class);
- if (getAllDataTypes.isRight()) {
- JanusGraphOperationStatus status = getAllDataTypes.right().value();
- if (status != JanusGraphOperationStatus.NOT_FOUND) {
- return Either.right(status);
- } else {
- return result;
- }
- }
-
- List<DataTypeData> list = getAllDataTypes.left().value();
- if (list != null) {
-
- log.trace("Number of data types to load is {}" , list.size());
-
- List<String> collect = list.stream().map(p -> p.getDataTypeDataDefinition().getName()).collect(Collectors.toList());
- log.trace("The data types to load are {}" , collect);
-
- for (DataTypeData dataTypeData : list) {
-
- log.trace("Going to fetch data type {}. uid is {}", dataTypeData.getDataTypeDataDefinition().getName(), dataTypeData.getUniqueId());
- Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = this.getAndAddDataTypeByUid(dataTypeData.getUniqueId(), dataTypes);
- if (dataTypeByUid.isRight()) {
- JanusGraphOperationStatus status = dataTypeByUid.right().value();
- if (status == JanusGraphOperationStatus.NOT_FOUND) {
- status = JanusGraphOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
- }
- }
-
- if (log.isTraceEnabled()) {
- if (result.isRight()) {
- log.trace("After fetching all data types {}" , result);
- } else {
- Map<String, DataTypeDefinition> map = result.left().value();
- if (map != null) {
- String types = map.keySet().stream().collect(Collectors.joining(",", "[", "]"));
- log.trace("After fetching all data types {} " , types);
- }
- }
- }
-
- return result;
- }
-
- /**
- * Build Data type object from graph by unique id
- *
- * @param uniqueId
- * @return
- */
- private Either<DataTypeDefinition, JanusGraphOperationStatus> getAndAddDataTypeByUid(String uniqueId, Map<String, DataTypeDefinition> allDataTypes) {
-
- Either<DataTypeDefinition, JanusGraphOperationStatus> result = null;
-
- if (allDataTypes.containsKey(uniqueId)) {
- return Either.left(allDataTypes.get(uniqueId));
- }
-
- Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
-
- if (dataTypesRes.isRight()) {
- JanusGraphOperationStatus status = dataTypesRes.right().value();
- log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
- return Either.right(status);
- }
-
- DataTypeData ctData = dataTypesRes.left().value();
- DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
-
- JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
- if (propertiesStatus != JanusGraphOperationStatus.OK) {
- log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
- return Either.right(propertiesStatus);
- }
-
- allDataTypes.put(dataTypeDefinition.getName(), dataTypeDefinition);
-
- String derivedFrom = dataTypeDefinition.getDerivedFromName();
- if (allDataTypes.containsKey(derivedFrom)) {
- DataTypeDefinition parentDataTypeDefinition = allDataTypes.get(derivedFrom);
-
- dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
-
- return Either.left(dataTypeDefinition);
- }
-
- Either<ImmutablePair<DataTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
- DataTypeData.class);
- log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode);
- if (parentNode.isRight()) {
- JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
- if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
- log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId,
- janusGraphOperationStatus);
- result = Either.right(janusGraphOperationStatus);
- return result;
- }
- } else {
- // derived from node was found
- ImmutablePair<DataTypeData, GraphEdge> immutablePair = parentNode.left().value();
- DataTypeData parentCT = immutablePair.getKey();
-
- String parentUniqueId = parentCT.getUniqueId();
- Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(parentUniqueId);
-
- if (dataTypeByUid.isRight()) {
- return Either.right(dataTypeByUid.right().value());
- }
-
- DataTypeDefinition parentDataTypeDefinition = dataTypeByUid.left().value();
-
- dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
-
- }
- result = Either.left(dataTypeDefinition);
-
- return result;
- }
-
- public Either<String, JanusGraphOperationStatus> checkInnerType(PropertyDataDefinition propDataDef) {
-
- String propertyType = propDataDef.getType();
-
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
-
- return getInnerType(type, propDataDef::getSchema);
- }
-
- public Either<List<DataTypeData>, JanusGraphOperationStatus> getAllDataTypeNodes() {
- Either<List<DataTypeData>, JanusGraphOperationStatus> getAllDataTypes = janusGraphGenericDao
- .getByCriteria(NodeTypeEnum.DataType, null, DataTypeData.class);
- if (getAllDataTypes.isRight()) {
- JanusGraphOperationStatus status = getAllDataTypes.right().value();
- if (status == JanusGraphOperationStatus.NOT_FOUND) {
- status = JanusGraphOperationStatus.OK;
- return Either.right(status);
- }
- }
- return getAllDataTypes;
- }
-
- public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> 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<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
- if (Boolean.FALSE.equals(validateResult.right)) {
- log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType);
- return Either.right(false);
- }
- JsonElement jsonElement = validateResult.left;
- String valueFromJsonElement = getValueFromJsonElement(jsonElement);
- return Either.left(valueFromJsonElement);
- }
- log.trace("before validating property type {}", propertyType);
- boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
- if (!isValidProperty) {
- log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type);
- return Either.right(false);
- }
- }
- Object convertedValue = value;
- if (!isEmptyValue(value) && isValidate) {
- PropertyValueConverter converter = type.getConverter();
- convertedValue = converter.convert(value, innerType, dataTypes);
- }
- return Either.left(convertedValue);
- }
-
- public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- return validateAndUpdatePropertyValue(propertyType, value, true, innerType, dataTypes);
- }
-
- public <T extends GraphNode> Either<List<PropertyDefinition>, StorageOperationStatus> getAllPropertiesRec(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz) {
- return this.findPropertiesOfNode(nodeType, uniqueId)
- .right()
- .bind(this::handleNotFoundProperties)
- .left()
- .bind(props -> getAllDerivedFromChainProperties(uniqueId, nodeType, clazz, props.values()));
- }
-
- private Either<Map<String, PropertyDefinition>, StorageOperationStatus> handleNotFoundProperties(JanusGraphOperationStatus janusGraphOperationStatus) {
- if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) {
- return Either.left(new HashMap<>());
- }
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- janusGraphOperationStatus));
- }
-
- private <T extends GraphNode> Either<List<PropertyDefinition>, StorageOperationStatus> getAllDerivedFromChainProperties(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz, Collection<PropertyDefinition> nodeProps) {
- List<PropertyDefinition> accumulatedProps = new ArrayList<>(nodeProps);
- String currentNodeUid = uniqueId;
- Either<T, StorageOperationStatus> derivedFrom;
- while ((derivedFrom = derivedFromOperation.getDerivedFromChild(currentNodeUid, nodeType, clazz)).isLeft()) {
- currentNodeUid = derivedFrom.left().value().getUniqueId();
- JanusGraphOperationStatus
- janusGraphOperationStatus = fillPropertiesList(currentNodeUid, nodeType, accumulatedProps::addAll);
- if (janusGraphOperationStatus != JanusGraphOperationStatus.OK) {
- log.debug("failed to fetch properties for type {} with id {}", nodeType, currentNodeUid);
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
- janusGraphOperationStatus));
- }
- }
- StorageOperationStatus getDerivedResult = derivedFrom.right().value();
- return isReachedEndOfDerivedFromChain(getDerivedResult) ? Either.left(accumulatedProps) : Either.right(getDerivedResult);
- }
-
- private boolean isReachedEndOfDerivedFromChain(StorageOperationStatus getDerivedResult) {
- return getDerivedResult == StorageOperationStatus.NOT_FOUND;
- }
-
- /*
- * @Override public PropertyOperation getPropertyOperation() { return this; }
- */
+ } else {
+ return Either.left(true);
+ }
+ }
+
+ public Either<Boolean, JanusGraphOperationStatus> isDefinedInDataTypes(String propertyType) {
+ String dataTypeUid = UniqueIdBuilder.buildDataTypeUid(propertyType);
+ Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(dataTypeUid);
+ if (dataTypeByUid.isRight()) {
+ JanusGraphOperationStatus status = dataTypeByUid.right().value();
+ if (status == JanusGraphOperationStatus.NOT_FOUND) {
+ return Either.left(false);
+ }
+ return Either.right(status);
+ }
+ return Either.left(true);
+ }
+
+ public Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> getAllDataTypes() {
+ Map<String, DataTypeDefinition> dataTypes = new HashMap<>();
+ Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> result = Either.left(dataTypes);
+ Either<List<DataTypeData>, JanusGraphOperationStatus> getAllDataTypes = janusGraphGenericDao
+ .getByCriteria(NodeTypeEnum.DataType, null, DataTypeData.class);
+ if (getAllDataTypes.isRight()) {
+ JanusGraphOperationStatus status = getAllDataTypes.right().value();
+ if (status != JanusGraphOperationStatus.NOT_FOUND) {
+ return Either.right(status);
+ } else {
+ return result;
+ }
+ }
+ List<DataTypeData> list = getAllDataTypes.left().value();
+ if (list != null) {
+ log.trace("Number of data types to load is {}", list.size());
+ List<String> collect = list.stream().map(p -> p.getDataTypeDataDefinition().getName()).collect(Collectors.toList());
+ log.trace("The data types to load are {}", collect);
+ for (DataTypeData dataTypeData : list) {
+ log.trace("Going to fetch data type {}. uid is {}", dataTypeData.getDataTypeDataDefinition().getName(), dataTypeData.getUniqueId());
+ Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = this
+ .getAndAddDataTypeByUid(dataTypeData.getUniqueId(), dataTypes);
+ if (dataTypeByUid.isRight()) {
+ JanusGraphOperationStatus status = dataTypeByUid.right().value();
+ if (status == JanusGraphOperationStatus.NOT_FOUND) {
+ status = JanusGraphOperationStatus.INVALID_ID;
+ }
+ return Either.right(status);
+ }
+ }
+ }
+ if (log.isTraceEnabled()) {
+ if (result.isRight()) {
+ log.trace("After fetching all data types {}", result);
+ } else {
+ Map<String, DataTypeDefinition> map = result.left().value();
+ if (map != null) {
+ String types = map.keySet().stream().collect(Collectors.joining(",", "[", "]"));
+ log.trace("After fetching all data types {} ", types);
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Build Data type object from graph by unique id
+ *
+ * @param uniqueId
+ * @return
+ */
+ private Either<DataTypeDefinition, JanusGraphOperationStatus> getAndAddDataTypeByUid(String uniqueId,
+ Map<String, DataTypeDefinition> allDataTypes) {
+ Either<DataTypeDefinition, JanusGraphOperationStatus> result = null;
+ if (allDataTypes.containsKey(uniqueId)) {
+ return Either.left(allDataTypes.get(uniqueId));
+ }
+ Either<DataTypeData, JanusGraphOperationStatus> dataTypesRes = janusGraphGenericDao
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, DataTypeData.class);
+ if (dataTypesRes.isRight()) {
+ JanusGraphOperationStatus status = dataTypesRes.right().value();
+ log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
+ return Either.right(status);
+ }
+ DataTypeData ctData = dataTypesRes.left().value();
+ DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(ctData.getDataTypeDataDefinition());
+ JanusGraphOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition);
+ if (propertiesStatus != JanusGraphOperationStatus.OK) {
+ log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId);
+ return Either.right(propertiesStatus);
+ }
+ allDataTypes.put(dataTypeDefinition.getName(), dataTypeDefinition);
+ String derivedFrom = dataTypeDefinition.getDerivedFromName();
+ if (allDataTypes.containsKey(derivedFrom)) {
+ DataTypeDefinition parentDataTypeDefinition = allDataTypes.get(derivedFrom);
+ dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
+ return Either.left(dataTypeDefinition);
+ }
+ Either<ImmutablePair<DataTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
+ .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType,
+ DataTypeData.class);
+ log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode);
+ if (parentNode.isRight()) {
+ JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
+ if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
+ log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, janusGraphOperationStatus);
+ result = Either.right(janusGraphOperationStatus);
+ return result;
+ }
+ } else {
+ // derived from node was found
+ ImmutablePair<DataTypeData, GraphEdge> immutablePair = parentNode.left().value();
+ DataTypeData parentCT = immutablePair.getKey();
+ String parentUniqueId = parentCT.getUniqueId();
+ Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = getDataTypeByUid(parentUniqueId);
+ if (dataTypeByUid.isRight()) {
+ return Either.right(dataTypeByUid.right().value());
+ }
+ DataTypeDefinition parentDataTypeDefinition = dataTypeByUid.left().value();
+ dataTypeDefinition.setDerivedFrom(parentDataTypeDefinition);
+ }
+ result = Either.left(dataTypeDefinition);
+ return result;
+ }
+
+ public Either<String, JanusGraphOperationStatus> checkInnerType(PropertyDataDefinition propDataDef) {
+ String propertyType = propDataDef.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+ return getInnerType(type, propDataDef::getSchema);
+ }
+
+ public Either<List<DataTypeData>, JanusGraphOperationStatus> getAllDataTypeNodes() {
+ Either<List<DataTypeData>, JanusGraphOperationStatus> getAllDataTypes = janusGraphGenericDao
+ .getByCriteria(NodeTypeEnum.DataType, null, DataTypeData.class);
+ if (getAllDataTypes.isRight()) {
+ JanusGraphOperationStatus status = getAllDataTypes.right().value();
+ if (status == JanusGraphOperationStatus.NOT_FOUND) {
+ status = JanusGraphOperationStatus.OK;
+ return Either.right(status);
+ }
+ }
+ return getAllDataTypes;
+ }
+
+ public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType,
+ Map<String, DataTypeDefinition> 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<JsonElement, Boolean> validateResult = dataTypeValidatorConverter
+ .validateAndUpdate(value, dataTypeDefinition, dataTypes);
+ if (Boolean.FALSE.equals(validateResult.right)) {
+ log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType);
+ return Either.right(false);
+ }
+ JsonElement jsonElement = validateResult.left;
+ String valueFromJsonElement = getValueFromJsonElement(jsonElement);
+ return Either.left(valueFromJsonElement);
+ }
+ log.trace("before validating property type {}", propertyType);
+ boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
+ if (!isValidProperty) {
+ log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type);
+ return Either.right(false);
+ }
+ }
+ Object convertedValue = value;
+ if (!isEmptyValue(value) && isValidate) {
+ PropertyValueConverter converter = type.getConverter();
+ convertedValue = converter.convert(value, innerType, dataTypes);
+ }
+ return Either.left(convertedValue);
+ }
+
+ public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, String innerType,
+ Map<String, DataTypeDefinition> dataTypes) {
+ return validateAndUpdatePropertyValue(propertyType, value, true, innerType, dataTypes);
+ }
+
+ public <T extends GraphNode> Either<List<PropertyDefinition>, StorageOperationStatus> getAllPropertiesRec(String uniqueId, NodeTypeEnum nodeType,
+ Class<T> clazz) {
+ return this.findPropertiesOfNode(nodeType, uniqueId).right().bind(this::handleNotFoundProperties).left()
+ .bind(props -> getAllDerivedFromChainProperties(uniqueId, nodeType, clazz, props.values()));
+ }
+
+ private Either<Map<String, PropertyDefinition>, StorageOperationStatus> handleNotFoundProperties(
+ JanusGraphOperationStatus janusGraphOperationStatus) {
+ if (janusGraphOperationStatus == JanusGraphOperationStatus.NOT_FOUND) {
+ return Either.left(new HashMap<>());
+ }
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
+ }
+
+ private <T extends GraphNode> Either<List<PropertyDefinition>, StorageOperationStatus> getAllDerivedFromChainProperties(String uniqueId,
+ NodeTypeEnum nodeType,
+ Class<T> clazz,
+ Collection<PropertyDefinition> nodeProps) {
+ List<PropertyDefinition> accumulatedProps = new ArrayList<>(nodeProps);
+ String currentNodeUid = uniqueId;
+ Either<T, StorageOperationStatus> derivedFrom;
+ while ((derivedFrom = derivedFromOperation.getDerivedFromChild(currentNodeUid, nodeType, clazz)).isLeft()) {
+ currentNodeUid = derivedFrom.left().value().getUniqueId();
+ JanusGraphOperationStatus janusGraphOperationStatus = fillPropertiesList(currentNodeUid, nodeType, accumulatedProps::addAll);
+ if (janusGraphOperationStatus != JanusGraphOperationStatus.OK) {
+ log.debug("failed to fetch properties for type {} with id {}", nodeType, currentNodeUid);
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus));
+ }
+ }
+ StorageOperationStatus getDerivedResult = derivedFrom.right().value();
+ return isReachedEndOfDerivedFromChain(getDerivedResult) ? Either.left(accumulatedProps) : Either.right(getDerivedResult);
+ }
+
+ private boolean isReachedEndOfDerivedFromChain(StorageOperationStatus getDerivedResult) {
+ return getDerivedResult == StorageOperationStatus.NOT_FOUND;
+ }
+
+ /*
+ * @Override public PropertyOperation getPropertyOperation() { return this; }
+ */
public JanusGraphOperationStatus fillPropertiesList(String uniqueId, NodeTypeEnum nodeType, Consumer<List<PropertyDefinition>> propertySetter) {
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesRes = findPropertiesifExist(uniqueId, nodeType);
- if (findPropertiesRes.isRight()) {
- return findPropertiesRes.right().value();
- }
- Map<String, PropertyDefinition> properties = findPropertiesRes.left().value();
- if (properties != null) {
- List<PropertyDefinition> propertiesAsList = properties.entrySet().stream().map(Entry::getValue).collect(Collectors.toList());
- propertySetter.accept(propertiesAsList);
- }
- return JanusGraphOperationStatus.OK;
- }
-
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesifExist(String uniqueId, NodeTypeEnum nodeType){
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(nodeType, uniqueId);
- if (findPropertiesOfNode.isRight()) {
- log.debug("After looking for properties of vertex {}. status is {}", uniqueId, findPropertiesOfNode.right().value());
- if(findPropertiesOfNode.right().value() == JanusGraphOperationStatus.NOT_FOUND)
- return Either.left(Maps.newHashMap());
- return findPropertiesOfNode;
- }
- return findPropertiesOfNode;
- }
-
- /**
- * add properties to element type.
- *
- * Per property, add a property node and associate it to the element type
- *
- * @param uniqueId
- * @param propertiesMap
- *
- * @return
- */
- protected Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum nodeType, Map<String, PropertyDefinition> propertiesMap) {
-
- Map<String, PropertyData> propertiesData = new HashMap<>();
-
- if (propertiesMap != null) {
-
- for (Entry<String, PropertyDefinition> propertyDefinitionEntry : propertiesMap.entrySet()) {
- String propertyName = propertyDefinitionEntry.getKey();
-
- Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType = this.addPropertyToNodeType(propertyName, propertyDefinitionEntry.getValue(), nodeType, uniqueId);
-
- if (addPropertyToNodeType.isRight()) {
- JanusGraphOperationStatus operationStatus = addPropertyToNodeType.right().value();
- log.error("Failed to associate {} {} to property {} in graph. status is {}", nodeType.getName(), uniqueId, propertyName, operationStatus);
- return Either.right(operationStatus);
- }
- propertiesData.put(propertyName, addPropertyToNodeType.left().value());
-
- }
- }
-
- return Either.left(propertiesData);
-
- }
-
- public Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum elementType, List<PropertyDefinition> properties) {
-
- Map<String, PropertyDefinition> propMap;
- if (properties == null) {
- propMap = null;
- } else {
- propMap = properties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, propDef -> propDef));
- }
- return addPropertiesToElementType(uniqueId, elementType, propMap);
- }
-
- @Override
- public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition) {
- return updateDataType(newDataTypeDefinition, oldDataTypeDefinition, true);
- }
-
- private Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition, boolean inTransaction) {
-
- Either<DataTypeDefinition, StorageOperationStatus> result = null;
-
- try {
-
- List<PropertyDefinition> newProperties = newDataTypeDefinition.getProperties();
-
- List<PropertyDefinition> oldProperties = oldDataTypeDefinition.getProperties();
-
- String newDerivedFromName = newDataTypeDefinition.getDerivedFromName();
-
- String oldDerivedFromName = oldDataTypeDefinition.getDerivedFromName();
-
- String dataTypeName = newDataTypeDefinition.getName();
-
- List<PropertyDefinition> propertiesToAdd = new ArrayList<>();
- if (isPropertyOmitted(newProperties, oldProperties, dataTypeName) || isPropertyTypeChanged(dataTypeName, newProperties, oldProperties, propertiesToAdd) || isDerivedFromNameChanged(dataTypeName, newDerivedFromName, oldDerivedFromName)) {
-
- log.debug("The new data type {} is invalid.", dataTypeName);
-
- result = Either.right(StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY);
- return result;
- }
-
- if (propertiesToAdd == null || propertiesToAdd.isEmpty()) {
- log.debug("No new properties has been defined in the new data type {}", newDataTypeDefinition);
- result = Either.right(StorageOperationStatus.OK);
- return result;
- }
- Map<String, String> newDescriptions = getPropertyDescriptionsToUpdate(oldProperties, newProperties);
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesRes = findPropertiesifExist(uniqueId, nodeType);
+ if (findPropertiesRes.isRight()) {
+ return findPropertiesRes.right().value();
+ }
+ Map<String, PropertyDefinition> properties = findPropertiesRes.left().value();
+ if (properties != null) {
+ List<PropertyDefinition> propertiesAsList = properties.entrySet().stream().map(Entry::getValue).collect(Collectors.toList());
+ propertySetter.accept(propertiesAsList);
+ }
+ return JanusGraphOperationStatus.OK;
+ }
- if(MapUtils.isNotEmpty(newDescriptions)){
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesifExist(String uniqueId, NodeTypeEnum nodeType) {
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(nodeType, uniqueId);
+ if (findPropertiesOfNode.isRight()) {
+ log.debug("After looking for properties of vertex {}. status is {}", uniqueId, findPropertiesOfNode.right().value());
+ if (findPropertiesOfNode.right().value() == JanusGraphOperationStatus.NOT_FOUND) {
+ return Either.left(Maps.newHashMap());
+ }
+ return findPropertiesOfNode;
+ }
+ return findPropertiesOfNode;
+ }
+
+ /**
+ * add properties to element type.
+ * <p>
+ * Per property, add a property node and associate it to the element type
+ *
+ * @param uniqueId
+ * @param propertiesMap
+ * @return
+ */
+ protected Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum nodeType,
+ Map<String, PropertyDefinition> propertiesMap) {
+ Map<String, PropertyData> propertiesData = new HashMap<>();
+ if (propertiesMap != null) {
+ for (Entry<String, PropertyDefinition> propertyDefinitionEntry : propertiesMap.entrySet()) {
+ String propertyName = propertyDefinitionEntry.getKey();
+ Either<PropertyData, JanusGraphOperationStatus> addPropertyToNodeType = this
+ .addPropertyToNodeType(propertyName, propertyDefinitionEntry.getValue(), nodeType, uniqueId);
+ if (addPropertyToNodeType.isRight()) {
+ JanusGraphOperationStatus operationStatus = addPropertyToNodeType.right().value();
+ log.error("Failed to associate {} {} to property {} in graph. status is {}", nodeType.getName(), uniqueId, propertyName,
+ operationStatus);
+ return Either.right(operationStatus);
+ }
+ propertiesData.put(propertyName, addPropertyToNodeType.left().value());
+ }
+ }
+ return Either.left(propertiesData);
+ }
+
+ public Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum elementType,
+ List<PropertyDefinition> properties) {
+ Map<String, PropertyDefinition> propMap;
+ if (properties == null) {
+ propMap = null;
+ } else {
+ propMap = properties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, propDef -> propDef));
+ }
+ return addPropertiesToElementType(uniqueId, elementType, propMap);
+ }
+
+ @Override
+ public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition,
+ DataTypeDefinition oldDataTypeDefinition) {
+ return updateDataType(newDataTypeDefinition, oldDataTypeDefinition, true);
+ }
- JanusGraphOperationStatus updatePropertiesStatus = updateDataTypePropertyDescriptions(oldDataTypeDefinition.getUniqueId(), newDescriptions);
+ private Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition,
+ DataTypeDefinition oldDataTypeDefinition, boolean inTransaction) {
+ Either<DataTypeDefinition, StorageOperationStatus> result = null;
+ try {
+ List<PropertyDefinition> newProperties = newDataTypeDefinition.getProperties();
+ List<PropertyDefinition> oldProperties = oldDataTypeDefinition.getProperties();
+ String newDerivedFromName = newDataTypeDefinition.getDerivedFromName();
+ String oldDerivedFromName = oldDataTypeDefinition.getDerivedFromName();
+ String dataTypeName = newDataTypeDefinition.getName();
+ List<PropertyDefinition> propertiesToAdd = new ArrayList<>();
+ if (isPropertyOmitted(newProperties, oldProperties, dataTypeName) || isPropertyTypeChanged(dataTypeName, newProperties, oldProperties,
+ propertiesToAdd) || isDerivedFromNameChanged(dataTypeName, newDerivedFromName, oldDerivedFromName)) {
+ log.debug("The new data type {} is invalid.", dataTypeName);
+ result = Either.right(StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY);
+ return result;
+ }
+ if (propertiesToAdd == null || propertiesToAdd.isEmpty()) {
+ log.debug("No new properties has been defined in the new data type {}", newDataTypeDefinition);
+ result = Either.right(StorageOperationStatus.OK);
+ return result;
+ }
+ Map<String, String> newDescriptions = getPropertyDescriptionsToUpdate(oldProperties, newProperties);
+ if (MapUtils.isNotEmpty(newDescriptions)) {
+ JanusGraphOperationStatus updatePropertiesStatus = updateDataTypePropertyDescriptions(oldDataTypeDefinition.getUniqueId(),
+ newDescriptions);
if (updatePropertiesStatus != JanusGraphOperationStatus.OK) {
- log.debug("#updateDataType - Failed to update the descriptions of the properties of the data type {}. Status is {}", oldDataTypeDefinition, updatePropertiesStatus);
+ log.debug("#updateDataType - Failed to update the descriptions of the properties of the data type {}. Status is {}",
+ oldDataTypeDefinition, updatePropertiesStatus);
BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError(UPDATE_DATA_TYPE, PROPERTY);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updatePropertiesStatus));
return result;
}
}
+ Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType = addPropertiesToDataType(
+ oldDataTypeDefinition.getUniqueId(), propertiesToAdd);
+ if (addPropertiesToDataType.isRight()) {
+ log.debug("Failed to update data type {} to Graph. Status is {}", oldDataTypeDefinition,
+ addPropertiesToDataType.right().value().name());
+ BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError(UPDATE_DATA_TYPE, PROPERTY);
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertiesToDataType.right().value()));
+ return result;
+ } else {
+ Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = this.getDataTypeByUid(oldDataTypeDefinition.getUniqueId());
+ if (dataTypeByUid.isRight()) {
+ JanusGraphOperationStatus status = addPropertiesToDataType.right().value();
+ log.debug("Failed to get data type {} after update. Status is {}", oldDataTypeDefinition.getUniqueId(), status.name());
+ BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(UPDATE_DATA_TYPE, PROPERTY, status.name());
+ result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
+ } else {
+ result = Either.left(dataTypeByUid.left().value());
+ }
+ }
+ return result;
+ } finally {
+ if (!inTransaction) {
+ if (result == null || result.isRight()) {
+ log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
+ janusGraphGenericDao.rollback();
+ } else {
+ log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
+ janusGraphGenericDao.commit();
+ }
+ }
+ }
+ }
- Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToDataType = addPropertiesToDataType(oldDataTypeDefinition.getUniqueId(), propertiesToAdd);
-
- if (addPropertiesToDataType.isRight()) {
- log.debug("Failed to update data type {} to Graph. Status is {}", oldDataTypeDefinition, addPropertiesToDataType.right().value().name());
- BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError(UPDATE_DATA_TYPE, PROPERTY);
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertiesToDataType.right().value()));
- return result;
- } else {
-
- Either<DataTypeDefinition, JanusGraphOperationStatus> dataTypeByUid = this.getDataTypeByUid(oldDataTypeDefinition.getUniqueId());
- if (dataTypeByUid.isRight()) {
- JanusGraphOperationStatus status = addPropertiesToDataType.right().value();
- log.debug("Failed to get data type {} after update. Status is {}", oldDataTypeDefinition.getUniqueId(), status.name());
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(UPDATE_DATA_TYPE, PROPERTY, status.name());
- result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
- } else {
- result = Either.left(dataTypeByUid.left().value());
- }
- }
-
- return result;
-
- } finally {
- if (!inTransaction) {
- if (result == null || result.isRight()) {
- log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH);
- janusGraphGenericDao.rollback();
- } else {
- log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH);
- janusGraphGenericDao.commit();
- }
- }
- }
-
- }
-
- private boolean isPropertyTypeChanged(String dataTypeName, List<PropertyDefinition> newProperties, List<PropertyDefinition> oldProperties, List<PropertyDefinition> outputPropertiesToAdd) {
-
- if (newProperties != null && oldProperties != null) {
-
- Map<String, PropertyDefinition> newPropsMapper = newProperties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
- Map<String, PropertyDefinition> oldPropsMapper = oldProperties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
-
- for (Entry<String, PropertyDefinition> newPropertyEntry : newPropsMapper.entrySet()) {
-
- String propName = newPropertyEntry.getKey();
- PropertyDefinition propDef = newPropertyEntry.getValue();
-
- PropertyDefinition oldPropertyDefinition = oldPropsMapper.get(propName);
- if (oldPropertyDefinition == null) {
- log.debug("New property {} received in the data type {}", propName, dataTypeName);
- outputPropertiesToAdd.add(propDef);
- continue;
- }
-
- String oldType = oldPropertyDefinition.getType();
- String oldEntryType = getEntryType(oldPropertyDefinition);
-
- String newType = propDef.getType();
- String newEntryType = getEntryType(propDef);
-
- if (!oldType.equals(newType)) {
- log.debug("Existing property {} in data type {} has a differnet type {} than the new one {}", propName, dataTypeName, oldType, newType);
- return true;
- }
-
- if (!equalsEntryTypes(oldEntryType, newEntryType)) {
- log.debug("Existing property {} in data type {} has a differnet entry type {} than the new one {}", propName, dataTypeName, oldEntryType, newEntryType);
- return true;
- }
-
- }
-
- }
-
- return false;
- }
-
- private boolean equalsEntryTypes(String oldEntryType, String newEntryType) {
-
- if (oldEntryType == null && newEntryType == null) {
- return true;
- } else if (oldEntryType != null && newEntryType != null) {
- return oldEntryType.equals(newEntryType);
- } else {
- return false;
- }
- }
-
- private String getEntryType(PropertyDefinition oldPropertyDefinition) {
- String entryType = null;
- SchemaDefinition schema = oldPropertyDefinition.getSchema();
- if (schema != null) {
- PropertyDataDefinition schemaProperty = schema.getProperty();
- if (schemaProperty != null) {
- entryType = schemaProperty.getType();
- }
- }
- return entryType;
- }
-
- private boolean isPropertyOmitted(List<PropertyDefinition> newProperties, List<PropertyDefinition> oldProperties, String dataTypeName) {
-
- boolean isValid = validateChangeInCaseOfEmptyProperties(newProperties, oldProperties, dataTypeName);
- if (!isValid) {
- log.debug("At least one property is missing in the new data type {}", dataTypeName);
- return false;
- }
-
- if (newProperties != null && oldProperties != null) {
-
- List<String> newProps = newProperties.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList());
- List<String> oldProps = oldProperties.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList());
-
- if (!newProps.containsAll(oldProps)) {
- StringJoiner joiner = new StringJoiner(",", "[", "]");
- newProps.forEach(joiner::add);
- log.debug("Properties {} in data type {} are missing, but they already defined in the existing data type", joiner.toString(), dataTypeName);
- return true;
- }
-
- }
- return false;
- }
-
- private boolean validateChangeInCaseOfEmptyProperties(List<PropertyDefinition> newProperties, List<PropertyDefinition> oldProperties, String dataTypeName) {
-
- if (newProperties != null) {
- if (newProperties.isEmpty()) {
- newProperties = null;
- }
- }
-
- if (oldProperties != null) {
- if (oldProperties.isEmpty()) {
- oldProperties = null;
- }
- }
-
- if ((newProperties == null && oldProperties == null) || (newProperties != null && oldProperties != null)) {
- return true;
- }
-
- return false;
- }
-
- private boolean isDerivedFromNameChanged(String dataTypeName, String newDerivedFromName, String oldDerivedFromName) {
-
- if (newDerivedFromName != null) {
- boolean isEqual = newDerivedFromName.equals(oldDerivedFromName);
- if (!isEqual) {
- log.debug("The new datatype {} derived from another data type {} than the existing one {}", dataTypeName, newDerivedFromName, oldDerivedFromName);
- }
- return !isEqual;
- } else if (oldDerivedFromName == null) {
- return false;
- } else {// new=null, old != null
- log.debug("The new datatype {} derived from another data type {} than the existing one {}", dataTypeName, newDerivedFromName, oldDerivedFromName);
- return true;
- }
-
- }
-
- /**
- * @param instanceId
- * @param nodeType
- * @return
- */
- public Either<Integer, StorageOperationStatus> increaseAndGetObjInstancePropertyCounter(String instanceId, NodeTypeEnum nodeType) {
- Either<JanusGraph, JanusGraphOperationStatus> graphResult = janusGraphGenericDao.getGraph();
- if (graphResult.isRight()) {
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graphResult.right().value()));
- }
- Either<JanusGraphVertex, JanusGraphOperationStatus> vertexService = janusGraphGenericDao
- .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), instanceId);
- if (vertexService.isRight()) {
- log.debug("failed to fetch vertex of resource instance for id = {}", instanceId);
- return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexService.right().value()));
- }
- Vertex vertex = vertexService.left().value();
-
- VertexProperty<Object> vertexProperty = vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty());
- Integer counter = 0;
- if (vertexProperty.isPresent() && vertexProperty.value() != null) {
- counter = (Integer) vertexProperty.value();
- }
-
- counter++;
- vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty(), counter);
-
- return Either.left(counter);
- }
-
-
- public Either<List<PropertyDefinition>, JanusGraphOperationStatus> validatePropertiesUniqueness(Map<String, PropertyDefinition> inheritedProperties, List<PropertyDefinition> properties) {
- Either<List<PropertyDefinition>, JanusGraphOperationStatus> result = Either.left(properties);
+ private boolean isPropertyTypeChanged(String dataTypeName, List<PropertyDefinition> newProperties, List<PropertyDefinition> oldProperties,
+ List<PropertyDefinition> outputPropertiesToAdd) {
+ if (newProperties != null && oldProperties != null) {
+ Map<String, PropertyDefinition> newPropsMapper = newProperties.stream()
+ .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
+ Map<String, PropertyDefinition> oldPropsMapper = oldProperties.stream()
+ .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
+ for (Entry<String, PropertyDefinition> newPropertyEntry : newPropsMapper.entrySet()) {
+ String propName = newPropertyEntry.getKey();
+ PropertyDefinition propDef = newPropertyEntry.getValue();
+ PropertyDefinition oldPropertyDefinition = oldPropsMapper.get(propName);
+ if (oldPropertyDefinition == null) {
+ log.debug("New property {} received in the data type {}", propName, dataTypeName);
+ outputPropertiesToAdd.add(propDef);
+ continue;
+ }
+ String oldType = oldPropertyDefinition.getType();
+ String oldEntryType = getEntryType(oldPropertyDefinition);
+ String newType = propDef.getType();
+ String newEntryType = getEntryType(propDef);
+ if (!oldType.equals(newType)) {
+ log.debug("Existing property {} in data type {} has a differnet type {} than the new one {}", propName, dataTypeName, oldType,
+ newType);
+ return true;
+ }
+ if (!equalsEntryTypes(oldEntryType, newEntryType)) {
+ log.debug("Existing property {} in data type {} has a differnet entry type {} than the new one {}", propName, dataTypeName,
+ oldEntryType, newEntryType);
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean equalsEntryTypes(String oldEntryType, String newEntryType) {
+ if (oldEntryType == null && newEntryType == null) {
+ return true;
+ } else if (oldEntryType != null && newEntryType != null) {
+ return oldEntryType.equals(newEntryType);
+ } else {
+ return false;
+ }
+ }
+
+ private String getEntryType(PropertyDefinition oldPropertyDefinition) {
+ String entryType = null;
+ SchemaDefinition schema = oldPropertyDefinition.getSchema();
+ if (schema != null) {
+ PropertyDataDefinition schemaProperty = schema.getProperty();
+ if (schemaProperty != null) {
+ entryType = schemaProperty.getType();
+ }
+ }
+ return entryType;
+ }
+
+ private boolean isPropertyOmitted(List<PropertyDefinition> newProperties, List<PropertyDefinition> oldProperties, String dataTypeName) {
+ boolean isValid = validateChangeInCaseOfEmptyProperties(newProperties, oldProperties, dataTypeName);
+ if (!isValid) {
+ log.debug("At least one property is missing in the new data type {}", dataTypeName);
+ return false;
+ }
+ if (newProperties != null && oldProperties != null) {
+ List<String> newProps = newProperties.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList());
+ List<String> oldProps = oldProperties.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList());
+ if (!newProps.containsAll(oldProps)) {
+ StringJoiner joiner = new StringJoiner(",", "[", "]");
+ newProps.forEach(joiner::add);
+ log.debug("Properties {} in data type {} are missing, but they already defined in the existing data type", joiner.toString(),
+ dataTypeName);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean validateChangeInCaseOfEmptyProperties(List<PropertyDefinition> newProperties, List<PropertyDefinition> oldProperties,
+ String dataTypeName) {
+ if (newProperties != null) {
+ if (newProperties.isEmpty()) {
+ newProperties = null;
+ }
+ }
+ if (oldProperties != null) {
+ if (oldProperties.isEmpty()) {
+ oldProperties = null;
+ }
+ }
+ if ((newProperties == null && oldProperties == null) || (newProperties != null && oldProperties != null)) {
+ return true;
+ }
+ return false;
+ }
+ private boolean isDerivedFromNameChanged(String dataTypeName, String newDerivedFromName, String oldDerivedFromName) {
+ if (newDerivedFromName != null) {
+ boolean isEqual = newDerivedFromName.equals(oldDerivedFromName);
+ if (!isEqual) {
+ log.debug("The new datatype {} derived from another data type {} than the existing one {}", dataTypeName, newDerivedFromName,
+ oldDerivedFromName);
+ }
+ return !isEqual;
+ } else if (oldDerivedFromName == null) {
+ return false;
+ } else {// new=null, old != null
+ log.debug("The new datatype {} derived from another data type {} than the existing one {}", dataTypeName, newDerivedFromName,
+ oldDerivedFromName);
+ return true;
+ }
+ }
+
+ /**
+ * @param instanceId
+ * @param nodeType
+ * @return
+ */
+ public Either<Integer, StorageOperationStatus> increaseAndGetObjInstancePropertyCounter(String instanceId, NodeTypeEnum nodeType) {
+ Either<JanusGraph, JanusGraphOperationStatus> graphResult = janusGraphGenericDao.getGraph();
+ if (graphResult.isRight()) {
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graphResult.right().value()));
+ }
+ Either<JanusGraphVertex, JanusGraphOperationStatus> vertexService = janusGraphGenericDao
+ .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), instanceId);
+ if (vertexService.isRight()) {
+ log.debug("failed to fetch vertex of resource instance for id = {}", instanceId);
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexService.right().value()));
+ }
+ Vertex vertex = vertexService.left().value();
+ VertexProperty<Object> vertexProperty = vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty());
+ Integer counter = 0;
+ if (vertexProperty.isPresent() && vertexProperty.value() != null) {
+ counter = (Integer) vertexProperty.value();
+ }
+ counter++;
+ vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty(), counter);
+ return Either.left(counter);
+ }
+
+ public Either<List<PropertyDefinition>, JanusGraphOperationStatus> validatePropertiesUniqueness(
+ Map<String, PropertyDefinition> inheritedProperties, List<PropertyDefinition> properties) {
+ Either<List<PropertyDefinition>, JanusGraphOperationStatus> result = Either.left(properties);
for (PropertyDefinition property : properties) {
- JanusGraphOperationStatus
- status = validatePropertyUniqueness(inheritedProperties, property);
+ JanusGraphOperationStatus status = validatePropertyUniqueness(inheritedProperties, property);
if (status != JanusGraphOperationStatus.OK) {
result = Either.right(status);
break;
}
}
-
return result;
}
/**
- * Validates uniqueness of examined property by comparing it with properties in propertiesOfType
- * and updates if need type and inner type of the property.
+ * Validates uniqueness of examined property by comparing it with properties in propertiesOfType and updates if need type and inner type of the
+ * property.
*/
private JanusGraphOperationStatus validatePropertyUniqueness(Map<String, PropertyDefinition> inheritedProperties, PropertyDefinition property) {
String propertyName = property.getName();
String propertyType = property.getType();
-
JanusGraphOperationStatus result = JanusGraphOperationStatus.OK;
if (inheritedProperties.containsKey(propertyName)) {
PropertyDefinition defaultProperty = inheritedProperties.get(propertyName);
@@ -2417,14 +1956,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
} else {
property.setType(defaultProperty.getType());
String innerType = defaultProperty.getSchemaType();
-
PropertyDataDefinition schemaProperty = property.getSchemaProperty();
if (schemaProperty != null) {
schemaProperty.setType(innerType);
}
}
}
-
return result;
}
@@ -2432,64 +1969,59 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return type1 != null && type2 != null && !type2.equals(type1);
}
-
- public <T extends GraphNode> Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getAllTypePropertiesFromAllDerivedFrom(String nextParentUid,
- NodeTypeEnum nodeType,
- Class<T> clazz) {
+ public <T extends GraphNode> Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getAllTypePropertiesFromAllDerivedFrom(
+ String nextParentUid, NodeTypeEnum nodeType, Class<T> clazz) {
Map<String, PropertyDefinition> allProperies = new HashMap<>();
return getTypePropertiesFromDerivedFromRecursively(nextParentUid, allProperies, nodeType, clazz);
}
- private <T extends GraphNode> Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getTypePropertiesFromDerivedFromRecursively(String nextParentUid,
- Map<String, PropertyDefinition> allProperies,
- NodeTypeEnum nodeType,
- Class<T> clazz) {
+ private <T extends GraphNode> Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getTypePropertiesFromDerivedFromRecursively(
+ String nextParentUid, Map<String, PropertyDefinition> allProperies, NodeTypeEnum nodeType, Class<T> clazz) {
JanusGraphOperationStatus error;
Either<List<ImmutablePair<T, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
- .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType),
- nextParentUid, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz);
+ .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), nextParentUid, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz);
if (childrenNodes.isRight()) {
if (childrenNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
error = childrenNodes.right().value();
- log.debug("#getTypePropertiesFromDerivedFromRecursively - Couldn't fetch derived from node with UID {}, error: {}", nextParentUid, error);
+ log.debug("#getTypePropertiesFromDerivedFromRecursively - Couldn't fetch derived from node with UID {}, error: {}", nextParentUid,
+ error);
return Either.right(error);
- }
- else {
- log.debug("#getTypePropertiesFromDerivedFromRecursively - Derived from node is not found with UID {} - this is OK for root.", nextParentUid);
+ } else {
+ log.debug("#getTypePropertiesFromDerivedFromRecursively - Derived from node is not found with UID {} - this is OK for root.",
+ nextParentUid);
return Either.left(allProperies);
}
} else {
-
Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> allPropertiesOfTypeRes = findPropertiesOfNode(nodeType, nextParentUid);
- if (allPropertiesOfTypeRes.isRight() && !allPropertiesOfTypeRes.right().value().equals(
- JanusGraphOperationStatus.NOT_FOUND)) {
+ if (allPropertiesOfTypeRes.isRight() && !allPropertiesOfTypeRes.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
error = allPropertiesOfTypeRes.right().value();
- log.error("#getTypePropertiesFromDerivedFromRecursively - Failed to retrieve properties for node with UID {} from graph. status is {}", nextParentUid, error);
+ log.error(
+ "#getTypePropertiesFromDerivedFromRecursively - Failed to retrieve properties for node with UID {} from graph. status is {}",
+ nextParentUid, error);
return Either.right(error);
} else if (allPropertiesOfTypeRes.isLeft()) {
if (allProperies.isEmpty()) {
allProperies.putAll(allPropertiesOfTypeRes.left().value());
} else {
- allProperies.putAll(allPropertiesOfTypeRes.left().value().entrySet().stream().filter(e -> !allProperies.containsKey(e.getKey())).collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
+ allProperies.putAll(allPropertiesOfTypeRes.left().value().entrySet().stream().filter(e -> !allProperies.containsKey(e.getKey()))
+ .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
}
}
- return getTypePropertiesFromDerivedFromRecursively(childrenNodes.left().value().get(0).getLeft().getUniqueId(), allProperies, nodeType, clazz);
+ return getTypePropertiesFromDerivedFromRecursively(childrenNodes.left().value().get(0).getLeft().getUniqueId(), allProperies, nodeType,
+ clazz);
}
}
- private JanusGraphOperationStatus updateDataTypePropertyDescriptions(String uniqueId, Map<String, String> newDescriptions) {
+ private JanusGraphOperationStatus updateDataTypePropertyDescriptions(String uniqueId, Map<String, String> newDescriptions) {
if (MapUtils.isNotEmpty(newDescriptions)) {
Either<List<ImmutablePair<JanusGraphVertex, Edge>>, JanusGraphOperationStatus> getDataTypePropertiesRes = janusGraphGenericDao
- .getChildrenVertecies(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.PROPERTY);
-
- if(getDataTypePropertiesRes.isRight()){
+ .getChildrenVertecies(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.PROPERTY);
+ if (getDataTypePropertiesRes.isRight()) {
log.debug("#updateDataTypePropertiesDescriptions - Failed to fetch the property verticies of the Data type {} ", uniqueId);
return getDataTypePropertiesRes.right().value();
}
- getDataTypePropertiesRes.left().value().stream()
- .filter(pair -> newDescriptions.containsKey(getPropertyNameFromEdge(pair)))
- .forEach(pair -> setNewDescriptionToVertex(newDescriptions.get(getPropertyNameFromEdge(pair)), pair));
-
+ getDataTypePropertiesRes.left().value().stream().filter(pair -> newDescriptions.containsKey(getPropertyNameFromEdge(pair)))
+ .forEach(pair -> setNewDescriptionToVertex(newDescriptions.get(getPropertyNameFromEdge(pair)), pair));
}
return JanusGraphOperationStatus.OK;
}
@@ -2503,27 +2035,176 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
}
private Map<String, String> getPropertyDescriptionsToUpdate(List<PropertyDefinition> oldProperties, List<PropertyDefinition> newProperties) {
-
- Map<String, PropertyDefinition> newPropertiesMap = newProperties
- .stream()
- .collect(Collectors.toMap(PropertyDefinition::getName, p->p));
-
- return oldProperties
- .stream()
- .filter(p-> newPropertiesMap.containsKey(p.getName()) && !descriptionsEqual(p, newPropertiesMap.get(p.getName())))
- .collect(Collectors.toMap(PropertyDefinition::getName, p->newPropertiesMap.get(p.getName()).getDescription()));
+ Map<String, PropertyDefinition> newPropertiesMap = newProperties.stream().collect(Collectors.toMap(PropertyDefinition::getName, p -> p));
+ return oldProperties.stream()
+ .filter(p -> newPropertiesMap.containsKey(p.getName()) && !descriptionsEqual(p, newPropertiesMap.get(p.getName())))
+ .collect(Collectors.toMap(PropertyDefinition::getName, p -> newPropertiesMap.get(p.getName()).getDescription()));
}
- private boolean descriptionsEqual(PropertyDefinition property, PropertyDefinition otherProperty){
- if(StringUtils.isEmpty(property.getDescription()) && StringUtils.isEmpty(otherProperty.getDescription())){
+ private boolean descriptionsEqual(PropertyDefinition property, PropertyDefinition otherProperty) {
+ if (StringUtils.isEmpty(property.getDescription()) && StringUtils.isEmpty(otherProperty.getDescription())) {
return true;
}
- if(StringUtils.isNotEmpty(property.getDescription()) && StringUtils.isEmpty(otherProperty.getDescription())){
+ if (StringUtils.isNotEmpty(property.getDescription()) && StringUtils.isEmpty(otherProperty.getDescription())) {
return false;
}
- if(StringUtils.isEmpty(property.getDescription()) && StringUtils.isNotEmpty(otherProperty.getDescription())){
+ if (StringUtils.isEmpty(property.getDescription()) && StringUtils.isNotEmpty(otherProperty.getDescription())) {
return false;
}
return property.getDescription().equals(otherProperty.getDescription());
}
+
+ public static class PropertyConstraintSerialiser implements JsonSerializer<PropertyConstraint> {
+
+ @Override
+ public JsonElement serialize(PropertyConstraint src, Type typeOfSrc, JsonSerializationContext context) {
+ JsonParser parser = new JsonParser();
+ JsonObject result = new JsonObject();
+ JsonArray jsonArray = new JsonArray();
+ if (src instanceof InRangeConstraint) {
+ InRangeConstraint rangeConstraint = (InRangeConstraint) src;
+ jsonArray.add(parser.parse(rangeConstraint.getRangeMinValue()));
+ jsonArray.add(parser.parse(rangeConstraint.getRangeMaxValue()));
+ result.add("inRange", jsonArray);
+ } else if (src instanceof GreaterThanConstraint) {
+ GreaterThanConstraint greaterThanConstraint = (GreaterThanConstraint) src;
+ jsonArray.add(parser.parse(greaterThanConstraint.getGreaterThan()));
+ result.add("greaterThan", jsonArray);
+ } else if (src instanceof LessOrEqualConstraint) {
+ LessOrEqualConstraint lessOrEqualConstraint = (LessOrEqualConstraint) src;
+ jsonArray.add(parser.parse(lessOrEqualConstraint.getLessOrEqual()));
+ result.add("lessOrEqual", jsonArray);
+ } else {
+ log.warn("PropertyConstraint {} is not supported. Ignored.", src.getClass().getName());
+ }
+ return result;
+ }
+ }
+
+ public static class PropertyConstraintDeserialiser implements JsonDeserializer<PropertyConstraint> {
+
+ private static final String THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL = "The value of GreaterThanConstraint is null";
+
+ @Override
+ public PropertyConstraint deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
+ PropertyConstraint propertyConstraint = null;
+ Set<Entry<String, JsonElement>> set = json.getAsJsonObject().entrySet();
+ if (set.size() == 1) {
+ Entry<String, JsonElement> element = set.iterator().next();
+ String key = element.getKey();
+ JsonElement value = element.getValue();
+ ConstraintType constraintType = ConstraintType.getByType(key);
+ if (constraintType == null) {
+ log.warn("ConstraintType was not found for constraint name:{}", key);
+ } else {
+ switch (constraintType) {
+ case IN_RANGE:
+ if (value != null) {
+ if (value instanceof JsonArray) {
+ JsonArray rangeArray = (JsonArray) value;
+ if (rangeArray.size() != 2) {
+ log.error("The range constraint content is invalid. value = {}", value);
+ } else {
+ InRangeConstraint rangeConstraint = new InRangeConstraint();
+ String minValue = rangeArray.get(0).getAsString();
+ String maxValue;
+ JsonElement maxElement = rangeArray.get(1);
+ if (maxElement.isJsonNull()) {
+ maxValue = String.valueOf(maxElement.getAsJsonNull());
+ } else {
+ maxValue = maxElement.getAsString();
+ }
+ rangeConstraint.setRangeMinValue(minValue);
+ rangeConstraint.setRangeMaxValue(maxValue);
+ propertyConstraint = rangeConstraint;
+ }
+ }
+ } else {
+ log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL);
+ }
+ break;
+ case GREATER_THAN:
+ if (value != null) {
+ String asString = value.getAsString();
+ log.debug("Before adding value to GreaterThanConstraint object. value = {}", asString);
+ propertyConstraint = new GreaterThanConstraint(asString);
+ break;
+ } else {
+ log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL);
+ }
+ break;
+ case LESS_THAN:
+ if (value != null) {
+ String asString = value.getAsString();
+ log.debug("Before adding value to LessThanConstraint object. value = {}", asString);
+ propertyConstraint = new LessThanConstraint(asString);
+ break;
+ } else {
+ log.warn("The value of LessThanConstraint is null");
+ }
+ break;
+ case GREATER_OR_EQUAL:
+ if (value != null) {
+ String asString = value.getAsString();
+ log.debug("Before adding value to GreaterThanConstraint object. value = {}", asString);
+ propertyConstraint = new GreaterOrEqualConstraint(asString);
+ break;
+ } else {
+ log.warn("The value of GreaterOrEqualConstraint is null");
+ }
+ break;
+ case LESS_OR_EQUAL:
+ if (value != null) {
+ String asString = value.getAsString();
+ log.debug("Before adding value to LessOrEqualConstraint object. value = {}", asString);
+ propertyConstraint = new LessOrEqualConstraint(asString);
+ } else {
+ log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL);
+ }
+ break;
+ case VALID_VALUES:
+ if (value != null) {
+ JsonArray rangeArray = (JsonArray) value;
+ if (rangeArray.size() == 0) {
+ log.error("The valid values constraint content is invalid. value = {}", value);
+ } else {
+ ValidValuesConstraint vvConstraint = new ValidValuesConstraint();
+ List<String> validValues = new ArrayList<>();
+ for (JsonElement jsonElement : rangeArray) {
+ String item = jsonElement.getAsString();
+ validValues.add(item);
+ }
+ vvConstraint.setValidValues(validValues);
+ propertyConstraint = vvConstraint;
+ }
+ }
+ break;
+ case MIN_LENGTH:
+ if (value != null) {
+ int asInt = value.getAsInt();
+ log.debug("Before adding value to Min Length object. value = {}", asInt);
+ propertyConstraint = new MinLengthConstraint(asInt);
+ break;
+ } else {
+ log.warn("The value of MinLengthConstraint is null");
+ }
+ break;
+ default:
+ log.warn("Key {} is not supported. Ignored.", key);
+ }
+ }
+ }
+ return propertyConstraint;
+ }
+ }
+
+ public static class PropertyConstraintJacksonDeserializer extends com.fasterxml.jackson.databind.JsonDeserializer<PropertyConstraint> {
+
+ @Override
+ public PropertyConstraint deserialize(com.fasterxml.jackson.core.JsonParser json, DeserializationContext context) throws IOException {
+ ObjectCodec oc = json.getCodec();
+ JsonNode node = oc.readTree(json);
+ return null;
+ }
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperation.java
index 7b0ee2e9d8..7fab326be7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RelationshipTypeOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
+import fj.data.Either;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
-import fj.data.Either;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
@@ -46,19 +44,15 @@ import org.springframework.stereotype.Component;
@Component("relationship-type-operation")
public class RelationshipTypeOperation extends AbstractOperation {
+ private static final Logger logger = Logger.getLogger(RelationshipTypeOperation.class.getName());
+ private static final String RELATIONSHIP_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS =
+ "Relationship type {} cannot be " + "found in " + "graph status is {}";
+ private static final String FAILED_TO_FETCH_PROPERTIES_OF_RELATIONSHIP_TYPE = "Failed to fetch properties of " + "relationship type {}";
@Autowired
private PropertyOperation propertyOperation;
-
@Autowired
private DerivedFromOperation derivedFromOperation;
- private static final Logger logger = Logger.getLogger(RelationshipTypeOperation.class.getName());
- private static final String RELATIONSHIP_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS = "Relationship type {} cannot be "
- + "found in "
- + "graph status is {}";
- private static final String FAILED_TO_FETCH_PROPERTIES_OF_RELATIONSHIP_TYPE = "Failed to fetch properties of "
- + "relationship type {}";
-
public Either<RelationshipTypeDefinition, JanusGraphOperationStatus> getRelationshipTypeByName(String name) {
String uid = UniqueIdBuilder.buildRelationshipTypeUid(name);
Either<RelationshipTypeDefinition, JanusGraphOperationStatus> result = getRelationshipTypeByUid(uid);
@@ -73,44 +67,34 @@ public class RelationshipTypeOperation extends AbstractOperation {
}
public Either<RelationshipTypeDefinition, JanusGraphOperationStatus> getRelationshipTypeByUid(String uniqueId) {
-
Either<RelationshipTypeDefinition, JanusGraphOperationStatus> result;
-
- Either<RelationshipTypeData, JanusGraphOperationStatus> relationshipTypesRes =
- janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(
- NodeTypeEnum.RelationshipType), uniqueId, RelationshipTypeData.class);
-
+ Either<RelationshipTypeData, JanusGraphOperationStatus> relationshipTypesRes = janusGraphGenericDao
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipType), uniqueId, RelationshipTypeData.class);
if (relationshipTypesRes.isRight()) {
JanusGraphOperationStatus status = relationshipTypesRes.right().value();
logger.debug("Relationship type {} cannot be found in graph. status is {}", uniqueId, status);
return Either.right(status);
}
-
RelationshipTypeData relationshipTypeData = relationshipTypesRes.left().value();
- RelationshipTypeDefinition relationshipTypeDefinition =
- new RelationshipTypeDefinition(relationshipTypeData.getRelationshipTypeDataDefinition());
-
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesStatus =
- OperationUtils.fillProperties(uniqueId, propertyOperation, NodeTypeEnum.RelationshipType);
+ RelationshipTypeDefinition relationshipTypeDefinition = new RelationshipTypeDefinition(
+ relationshipTypeData.getRelationshipTypeDataDefinition());
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesStatus = OperationUtils
+ .fillProperties(uniqueId, propertyOperation, NodeTypeEnum.RelationshipType);
if (propertiesStatus.isRight() && propertiesStatus.right().value() != JanusGraphOperationStatus.OK) {
logger.error("Failed to fetch properties of relationship type {}", uniqueId);
return Either.right(propertiesStatus.right().value());
}
-
if (propertiesStatus.isLeft()) {
relationshipTypeDefinition.setProperties(propertiesStatus.left().value());
}
-
Either<ImmutablePair<RelationshipTypeData, GraphEdge>, JanusGraphOperationStatus> parentNode = janusGraphGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipType), uniqueId,
- GraphEdgeLabels.DERIVED_FROM,
- NodeTypeEnum.RelationshipType, RelationshipTypeData.class);
+ .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipType), uniqueId, GraphEdgeLabels.DERIVED_FROM,
+ NodeTypeEnum.RelationshipType, RelationshipTypeData.class);
logger.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode);
if (parentNode.isRight()) {
JanusGraphOperationStatus janusGraphOperationStatus = parentNode.right().value();
if (janusGraphOperationStatus != JanusGraphOperationStatus.NOT_FOUND) {
- logger.error("Failed to find the parent relationship of relationship type {}. status is {}", uniqueId,
- janusGraphOperationStatus);
+ logger.error("Failed to find the parent relationship of relationship type {}. status is {}", uniqueId, janusGraphOperationStatus);
result = Either.right(janusGraphOperationStatus);
return result;
}
@@ -121,21 +105,19 @@ public class RelationshipTypeOperation extends AbstractOperation {
relationshipTypeDefinition.setDerivedFrom(parentCT.getRelationshipTypeDataDefinition().getType());
}
result = Either.left(relationshipTypeDefinition);
-
return result;
}
private Either<RelationshipTypeDefinition, StorageOperationStatus> validateUpdateProperties(
- RelationshipTypeDefinition relationshipTypeDefinition) {
+ RelationshipTypeDefinition relationshipTypeDefinition) {
JanusGraphOperationStatus error = null;
- if (MapUtils.isNotEmpty(relationshipTypeDefinition.getProperties())
- && relationshipTypeDefinition.getDerivedFrom() != null) {
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> allPropertiesRes =
- getAllRelationshipTypePropertiesFromAllDerivedFrom(relationshipTypeDefinition.getDerivedFrom());
+ if (MapUtils.isNotEmpty(relationshipTypeDefinition.getProperties()) && relationshipTypeDefinition.getDerivedFrom() != null) {
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> allPropertiesRes = getAllRelationshipTypePropertiesFromAllDerivedFrom(
+ relationshipTypeDefinition.getDerivedFrom());
if (allPropertiesRes.isRight() && !JanusGraphOperationStatus.NOT_FOUND.equals(allPropertiesRes.right().value())) {
error = allPropertiesRes.right().value();
- logger.debug("Couldn't fetch derived from property nodes for relationship type {}, error: {}",
- relationshipTypeDefinition.getType(), error);
+ logger.debug("Couldn't fetch derived from property nodes for relationship type {}, error: {}", relationshipTypeDefinition.getType(),
+ error);
}
error = getJanusGraphOperationStatus(relationshipTypeDefinition, error, allPropertiesRes);
}
@@ -146,18 +128,16 @@ public class RelationshipTypeOperation extends AbstractOperation {
}
private JanusGraphOperationStatus getJanusGraphOperationStatus(RelationshipTypeDefinition relationshipTypeDefinition,
- JanusGraphOperationStatus error,
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> allPropertiesRes) {
+ JanusGraphOperationStatus error,
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> allPropertiesRes) {
if (error == null && !allPropertiesRes.left().value().isEmpty()) {
Map<String, PropertyDefinition> derivedFromProperties = allPropertiesRes.left().value();
relationshipTypeDefinition.getProperties().entrySet().stream()
- .filter(e -> derivedFromProperties.containsKey(e.getKey()) && e.getValue().getType() == null)
- .forEach(e -> e.getValue().setType(derivedFromProperties.get(e.getKey()).getType()));
-
- List<PropertyDefinition>
- properties = new ArrayList<>(relationshipTypeDefinition.getProperties().values());
- Either<List<PropertyDefinition>, JanusGraphOperationStatus> validatePropertiesRes =
- propertyOperation.validatePropertiesUniqueness(allPropertiesRes.left().value(), properties);
+ .filter(e -> derivedFromProperties.containsKey(e.getKey()) && e.getValue().getType() == null)
+ .forEach(e -> e.getValue().setType(derivedFromProperties.get(e.getKey()).getType()));
+ List<PropertyDefinition> properties = new ArrayList<>(relationshipTypeDefinition.getProperties().values());
+ Either<List<PropertyDefinition>, JanusGraphOperationStatus> validatePropertiesRes = propertyOperation
+ .validatePropertiesUniqueness(allPropertiesRes.left().value(), properties);
if (validatePropertiesRes.isRight()) {
error = validatePropertiesRes.right().value();
}
@@ -166,40 +146,26 @@ public class RelationshipTypeOperation extends AbstractOperation {
}
private Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> getAllRelationshipTypePropertiesFromAllDerivedFrom(
- String firstParentType) {
- return propertyOperation.getAllTypePropertiesFromAllDerivedFrom(firstParentType, NodeTypeEnum.RelationshipType,
- RelationshipTypeData.class);
+ String firstParentType) {
+ return propertyOperation.getAllTypePropertiesFromAllDerivedFrom(firstParentType, NodeTypeEnum.RelationshipType, RelationshipTypeData.class);
}
- public Either<RelationshipTypeDefinition, StorageOperationStatus> addRelationshipType(
- RelationshipTypeDefinition relationshipTypeDefinition,
- boolean inTransaction) {
-
+ public Either<RelationshipTypeDefinition, StorageOperationStatus> addRelationshipType(RelationshipTypeDefinition relationshipTypeDefinition,
+ boolean inTransaction) {
Either<RelationshipTypeDefinition, StorageOperationStatus> result = null;
-
try {
- Either<RelationshipTypeDefinition, StorageOperationStatus> validationRes =
- validateUpdateProperties(relationshipTypeDefinition);
+ Either<RelationshipTypeDefinition, StorageOperationStatus> validationRes = validateUpdateProperties(relationshipTypeDefinition);
if (validationRes.isRight()) {
- logger.error(
- "#addRelationshipType - One or all properties of relationship type {} not valid. status is {}"
- , relationshipTypeDefinition, validationRes.right().value());
+ logger
+ .error("#addRelationshipType - One or all properties of relationship type {} not valid. status is {}", relationshipTypeDefinition,
+ validationRes.right().value());
return validationRes;
}
-
- Either<RelationshipTypeData, StorageOperationStatus> eitherStatus =
- addRelationshipTypeToGraph(relationshipTypeDefinition);
-
- result = eitherStatus.left()
- .map(RelationshipTypeData::getUniqueId)
- .left()
- .bind(uniqueId -> getRelationshipType(uniqueId, inTransaction));
-
+ Either<RelationshipTypeData, StorageOperationStatus> eitherStatus = addRelationshipTypeToGraph(relationshipTypeDefinition);
+ result = eitherStatus.left().map(RelationshipTypeData::getUniqueId).left().bind(uniqueId -> getRelationshipType(uniqueId, inTransaction));
if (result.isLeft()) {
- logger.debug("#addRelationshipType - The returned RelationshipTypeDefinition is {}",
- result.left().value());
+ logger.debug("#addRelationshipType - The returned RelationshipTypeDefinition is {}", result.left().value());
}
-
return result;
} finally {
if (!inTransaction) {
@@ -214,26 +180,19 @@ public class RelationshipTypeOperation extends AbstractOperation {
}
}
- public Either<RelationshipTypeDefinition, StorageOperationStatus> getRelationshipType(String uniqueId,
- boolean inTransaction) {
-
+ public Either<RelationshipTypeDefinition, StorageOperationStatus> getRelationshipType(String uniqueId, boolean inTransaction) {
Either<RelationshipTypeDefinition, StorageOperationStatus> result;
try {
-
Either<RelationshipTypeDefinition, JanusGraphOperationStatus> ctResult = this.getRelationshipTypeByUid(uniqueId);
-
if (ctResult.isRight()) {
JanusGraphOperationStatus status = ctResult.right().value();
if (status != JanusGraphOperationStatus.NOT_FOUND) {
- logger.error("Failed to retrieve information on relationship type {}. status is {}", uniqueId,
- status);
+ logger.error("Failed to retrieve information on relationship type {}. status is {}", uniqueId, status);
}
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(ctResult.right().value()));
return result;
}
-
result = Either.left(ctResult.left().value());
-
return result;
} finally {
if (!inTransaction) {
@@ -243,49 +202,32 @@ public class RelationshipTypeOperation extends AbstractOperation {
}
}
- private Either<RelationshipTypeData, StorageOperationStatus> addRelationshipTypeToGraph(
- RelationshipTypeDefinition relationshipTypeDefinition) {
-
+ private Either<RelationshipTypeData, StorageOperationStatus> addRelationshipTypeToGraph(RelationshipTypeDefinition relationshipTypeDefinition) {
logger.debug("Got relationship type {}", relationshipTypeDefinition);
-
String ctUniqueId = UniqueIdBuilder.buildRelationshipTypeUid(relationshipTypeDefinition.getType());
RelationshipTypeData relationshipTypeData = buildRelationshipTypeData(relationshipTypeDefinition, ctUniqueId);
-
logger.debug("Before adding relationship type to graph. relationshipTypeData = {}", relationshipTypeData);
- Either<RelationshipTypeData, JanusGraphOperationStatus> createCTResult =
- janusGraphGenericDao.createNode(relationshipTypeData, RelationshipTypeData.class);
+ Either<RelationshipTypeData, JanusGraphOperationStatus> createCTResult = janusGraphGenericDao
+ .createNode(relationshipTypeData, RelationshipTypeData.class);
logger.debug("After adding relationship type to graph. status is = {}", createCTResult);
-
if (createCTResult.isRight()) {
JanusGraphOperationStatus operationStatus = createCTResult.right().value();
- logger.error("Failed to relationship type {} to graph. status is {}", relationshipTypeDefinition.getType(),
- operationStatus);
+ logger.error("Failed to relationship type {} to graph. status is {}", relationshipTypeDefinition.getType(), operationStatus);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus));
}
-
RelationshipTypeData resultCTD = createCTResult.left().value();
Map<String, PropertyDefinition> propertiesMap = relationshipTypeDefinition.getProperties();
Either<Map<String, PropertyData>, JanusGraphOperationStatus> addPropertiesToRelationshipType = propertyOperation
- .addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.RelationshipType, propertiesMap);
+ .addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.RelationshipType, propertiesMap);
if (addPropertiesToRelationshipType.isRight()) {
- logger.error("Failed add properties {} to relationship {}", propertiesMap,
- relationshipTypeDefinition.getType());
- return Either.right(DaoStatusConverter
- .convertJanusGraphStatusToStorageStatus(addPropertiesToRelationshipType.right().value()));
+ logger.error("Failed add properties {} to relationship {}", propertiesMap, relationshipTypeDefinition.getType());
+ return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertiesToRelationshipType.right().value()));
}
-
- return addDerivedFromRelation(relationshipTypeDefinition, ctUniqueId)
- .left()
- .map(updatedDerivedFrom -> createCTResult.left().value());
-
-
+ return addDerivedFromRelation(relationshipTypeDefinition, ctUniqueId).left().map(updatedDerivedFrom -> createCTResult.left().value());
}
- private RelationshipTypeData buildRelationshipTypeData(RelationshipTypeDefinition relationshipTypeDefinition,
- String ctUniqueId) {
-
+ private RelationshipTypeData buildRelationshipTypeData(RelationshipTypeDefinition relationshipTypeDefinition, String ctUniqueId) {
RelationshipTypeData relationshipTypeData = new RelationshipTypeData(relationshipTypeDefinition);
-
relationshipTypeData.getRelationshipTypeDataDefinition().setUniqueId(ctUniqueId);
Long creationDate = relationshipTypeData.getRelationshipTypeDataDefinition().getCreationTime();
if (creationDate == null) {
@@ -296,39 +238,31 @@ public class RelationshipTypeOperation extends AbstractOperation {
return relationshipTypeData;
}
- private Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(
- RelationshipTypeDefinition relationshipTypeDefinition,
- String relationshipTypeUniqueId) {
+ private Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(RelationshipTypeDefinition relationshipTypeDefinition,
+ String relationshipTypeUniqueId) {
String derivedFrom = relationshipTypeDefinition.getDerivedFrom();
if (derivedFrom == null) {
return Either.left(null);
}
- logger.debug(
- "#addDerivedFromRelation - adding derived from relation between relationship type {} to its parent "
- + "{}", relationshipTypeDefinition.getType(), derivedFrom);
- return getRelationshipTypeByType(derivedFrom)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
- .left()
- .bind(derivedFromRelationship -> derivedFromOperation.addDerivedFromRelation(relationshipTypeUniqueId,
- derivedFromRelationship.getUniqueId(), NodeTypeEnum.RelationshipType));
+ logger.debug("#addDerivedFromRelation - adding derived from relation between relationship type {} to its parent " + "{}",
+ relationshipTypeDefinition.getType(), derivedFrom);
+ return getRelationshipTypeByType(derivedFrom).right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus).left().bind(
+ derivedFromRelationship -> derivedFromOperation
+ .addDerivedFromRelation(relationshipTypeUniqueId, derivedFromRelationship.getUniqueId(), NodeTypeEnum.RelationshipType));
}
- private Either<RelationshipTypeDefinition, JanusGraphOperationStatus> getRelationshipTypeByType(
- String relationshipType) {
+ private Either<RelationshipTypeDefinition, JanusGraphOperationStatus> getRelationshipTypeByType(String relationshipType) {
// Optimization: In case of Relationship Type its unique ID is the same as type
return getRelationshipTypeByUid(relationshipType);
}
- public Either<RelationshipTypeDefinition, StorageOperationStatus> updateRelationshipType(
- RelationshipTypeDefinition newRelationshipTypeDefinition,
- RelationshipTypeDefinition oldRelationshipTypeDefinition, boolean inTransaction) {
+ public Either<RelationshipTypeDefinition, StorageOperationStatus> updateRelationshipType(RelationshipTypeDefinition newRelationshipTypeDefinition,
+ RelationshipTypeDefinition oldRelationshipTypeDefinition,
+ boolean inTransaction) {
logger.debug("updating relationship type {}", newRelationshipTypeDefinition.getType());
Either<RelationshipTypeDefinition, StorageOperationStatus> updateRelationshipEither = null;
-
try {
- updateRelationshipEither =
- updateRelationshipTypeOnGraph(newRelationshipTypeDefinition, oldRelationshipTypeDefinition);
+ updateRelationshipEither = updateRelationshipTypeOnGraph(newRelationshipTypeDefinition, oldRelationshipTypeDefinition);
} finally {
if (!inTransaction) {
if (updateRelationshipEither == null || updateRelationshipEither.isRight()) {
@@ -342,42 +276,31 @@ public class RelationshipTypeOperation extends AbstractOperation {
}
private Either<RelationshipTypeDefinition, StorageOperationStatus> updateRelationshipTypeOnGraph(
- RelationshipTypeDefinition newRelationshipTypeDefinition,
- RelationshipTypeDefinition oldRelationshipTypeDefinition) {
+ RelationshipTypeDefinition newRelationshipTypeDefinition, RelationshipTypeDefinition oldRelationshipTypeDefinition) {
updateRelationshipTypeData(newRelationshipTypeDefinition, oldRelationshipTypeDefinition);
- return janusGraphGenericDao
- .updateNode(new RelationshipTypeData(newRelationshipTypeDefinition), RelationshipTypeData.class)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
- .left()
- .bind(updatedNode -> updateRelationshipTypeProperties(newRelationshipTypeDefinition.getUniqueId(),
- newRelationshipTypeDefinition.getProperties()))
- .left()
- .bind(updatedProperties -> updateRelationshipTypeDerivedFrom(newRelationshipTypeDefinition,
- oldRelationshipTypeDefinition.getDerivedFrom()))
- .left()
- .map(updatedDerivedFrom -> newRelationshipTypeDefinition);
+ return janusGraphGenericDao.updateNode(new RelationshipTypeData(newRelationshipTypeDefinition), RelationshipTypeData.class).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus).left().bind(
+ updatedNode -> updateRelationshipTypeProperties(newRelationshipTypeDefinition.getUniqueId(),
+ newRelationshipTypeDefinition.getProperties())).left().bind(
+ updatedProperties -> updateRelationshipTypeDerivedFrom(newRelationshipTypeDefinition, oldRelationshipTypeDefinition.getDerivedFrom()))
+ .left().map(updatedDerivedFrom -> newRelationshipTypeDefinition);
}
- private Either<Map<String, PropertyData>, StorageOperationStatus> updateRelationshipTypeProperties(
- String relationshipTypeId, Map<String, PropertyDefinition> properties) {
- logger.debug(
- "#updateRelationshipTypeProperties - updating relationship type properties for relationship type with "
- + "id {}", relationshipTypeId);
- return propertyOperation.deletePropertiesAssociatedToNode(NodeTypeEnum.RelationshipType, relationshipTypeId)
- .left()
- .bind(deleteProps -> addPropertiesToRelationshipType(relationshipTypeId, properties));
+ private Either<Map<String, PropertyData>, StorageOperationStatus> updateRelationshipTypeProperties(String relationshipTypeId,
+ Map<String, PropertyDefinition> properties) {
+ logger.debug("#updateRelationshipTypeProperties - updating relationship type properties for relationship type with " + "id {}",
+ relationshipTypeId);
+ return propertyOperation.deletePropertiesAssociatedToNode(NodeTypeEnum.RelationshipType, relationshipTypeId).left()
+ .bind(deleteProps -> addPropertiesToRelationshipType(relationshipTypeId, properties));
}
- private Either<GraphRelation, StorageOperationStatus> updateRelationshipTypeDerivedFrom(
- RelationshipTypeDefinition newRelationshipTypeDefinition, String currDerivedFromRelationshipType) {
+ private Either<GraphRelation, StorageOperationStatus> updateRelationshipTypeDerivedFrom(RelationshipTypeDefinition newRelationshipTypeDefinition,
+ String currDerivedFromRelationshipType) {
String relationshipTypeId = newRelationshipTypeDefinition.getUniqueId();
- logger.debug(
- "#updateRelationshipTypeDerivedFrom - updating relationship derived from relation for relationship "
- + "type with id {}. old derived type {}. new derived type {}", relationshipTypeId,
- currDerivedFromRelationshipType, newRelationshipTypeDefinition.getDerivedFrom());
- StorageOperationStatus deleteDerivedRelationStatus =
- deleteDerivedFromRelationshipType(relationshipTypeId, currDerivedFromRelationshipType);
+ logger.debug("#updateRelationshipTypeDerivedFrom - updating relationship derived from relation for relationship "
+ + "type with id {}. old derived type {}. new derived type {}", relationshipTypeId, currDerivedFromRelationshipType,
+ newRelationshipTypeDefinition.getDerivedFrom());
+ StorageOperationStatus deleteDerivedRelationStatus = deleteDerivedFromRelationshipType(relationshipTypeId, currDerivedFromRelationshipType);
if (deleteDerivedRelationStatus != StorageOperationStatus.OK) {
return Either.right(deleteDerivedRelationStatus);
}
@@ -391,39 +314,31 @@ public class RelationshipTypeOperation extends AbstractOperation {
newRelationshipTypeDefinition.setModificationTime(System.currentTimeMillis());
}
- private Either<Map<String, PropertyData>, StorageOperationStatus> addPropertiesToRelationshipType(
- String relationshipTypeId, Map<String, PropertyDefinition> properties) {
- logger.debug(
- "#addPropertiesToRelationshipType - adding relationship type properties for relationship type with "
- + "id {}", relationshipTypeId);
- return propertyOperation
- .addPropertiesToElementType(relationshipTypeId, NodeTypeEnum.RelationshipType, properties)
- .right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ private Either<Map<String, PropertyData>, StorageOperationStatus> addPropertiesToRelationshipType(String relationshipTypeId,
+ Map<String, PropertyDefinition> properties) {
+ logger.debug("#addPropertiesToRelationshipType - adding relationship type properties for relationship type with " + "id {}",
+ relationshipTypeId);
+ return propertyOperation.addPropertiesToElementType(relationshipTypeId, NodeTypeEnum.RelationshipType, properties).right()
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
- private StorageOperationStatus deleteDerivedFromRelationshipType(String relationshipTypeId,
- String derivedFromType) {
+ private StorageOperationStatus deleteDerivedFromRelationshipType(String relationshipTypeId, String derivedFromType) {
if (derivedFromType == null) {
return StorageOperationStatus.OK;
}
- logger.debug("#deleteDerivedFromRelationshipType - deleting derivedFrom relation for relationship type with id "
- + "{} and its derived type {}", relationshipTypeId, derivedFromType);
- return getRelationshipTypeByType(derivedFromType)
- .either(derivedFromNode -> derivedFromOperation
- .removeDerivedFromRelation(relationshipTypeId, derivedFromNode.getUniqueId(),
- NodeTypeEnum.RelationshipType),
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ logger
+ .debug("#deleteDerivedFromRelationshipType - deleting derivedFrom relation for relationship type with id " + "{} and its derived type {}",
+ relationshipTypeId, derivedFromType);
+ return getRelationshipTypeByType(derivedFromType).either(derivedFromNode -> derivedFromOperation
+ .removeDerivedFromRelation(relationshipTypeId, derivedFromNode.getUniqueId(), NodeTypeEnum.RelationshipType),
+ DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
public Either<Map<String, RelationshipTypeDefinition>, JanusGraphOperationStatus> getAllRelationshipTypes() {
-
Map<String, RelationshipTypeDefinition> relationshipTypeDefinitionMap = new HashMap<>();
Either<Map<String, RelationshipTypeDefinition>, JanusGraphOperationStatus> result = Either.left(relationshipTypeDefinitionMap);
-
- Either<List<RelationshipTypeData>, JanusGraphOperationStatus> getAllRelationshipTypes =
- janusGraphGenericDao
- .getByCriteria(NodeTypeEnum.RelationshipType, null, RelationshipTypeData.class);
+ Either<List<RelationshipTypeData>, JanusGraphOperationStatus> getAllRelationshipTypes = janusGraphGenericDao
+ .getByCriteria(NodeTypeEnum.RelationshipType, null, RelationshipTypeData.class);
if (getAllRelationshipTypes.isRight()) {
JanusGraphOperationStatus status = getAllRelationshipTypes.right().value();
if (status != JanusGraphOperationStatus.NOT_FOUND) {
@@ -432,32 +347,26 @@ public class RelationshipTypeOperation extends AbstractOperation {
return result;
}
}
-
List<RelationshipTypeData> list = getAllRelationshipTypes.left().value();
if (list != null) {
-
logger.trace("Number of relationship types to load is {}", list.size());
//Set properties
- Either<Map<String, RelationshipTypeDefinition>, JanusGraphOperationStatus> status =
- getMapJanusGraphOperationStatusEither(relationshipTypeDefinitionMap, list);
+ Either<Map<String, RelationshipTypeDefinition>, JanusGraphOperationStatus> status = getMapJanusGraphOperationStatusEither(
+ relationshipTypeDefinitionMap, list);
if (status != null) {
return status;
}
}
-
return result;
}
private Either<Map<String, RelationshipTypeDefinition>, JanusGraphOperationStatus> getMapJanusGraphOperationStatusEither(
- Map<String, RelationshipTypeDefinition> relationshipTypeDefinitionMap,
- List<RelationshipTypeData> list) {
+ Map<String, RelationshipTypeDefinition> relationshipTypeDefinitionMap, List<RelationshipTypeData> list) {
for (RelationshipTypeData relationshipTypeData : list) {
-
- logger.trace("Going to fetch relationship type {}. uid is {}",
- relationshipTypeData.getRelationshipTypeDataDefinition().getType(),
- relationshipTypeData.getUniqueId());
- Either<RelationshipTypeDefinition, JanusGraphOperationStatus> relationshipTypesByUid =
- getAndAddPropertiesANdDerivedFrom(relationshipTypeData.getUniqueId(), relationshipTypeDefinitionMap);
+ logger.trace("Going to fetch relationship type {}. uid is {}", relationshipTypeData.getRelationshipTypeDataDefinition().getType(),
+ relationshipTypeData.getUniqueId());
+ Either<RelationshipTypeDefinition, JanusGraphOperationStatus> relationshipTypesByUid = getAndAddPropertiesANdDerivedFrom(
+ relationshipTypeData.getUniqueId(), relationshipTypeDefinitionMap);
if (relationshipTypesByUid.isRight()) {
JanusGraphOperationStatus status = relationshipTypesByUid.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -469,53 +378,38 @@ public class RelationshipTypeOperation extends AbstractOperation {
return null;
}
- private Either<RelationshipTypeDefinition, JanusGraphOperationStatus> getAndAddPropertiesANdDerivedFrom(
- String uniqueId, Map<String, RelationshipTypeDefinition> relationshipTypeDefinitionMap) {
+ private Either<RelationshipTypeDefinition, JanusGraphOperationStatus> getAndAddPropertiesANdDerivedFrom(String uniqueId,
+ Map<String, RelationshipTypeDefinition> relationshipTypeDefinitionMap) {
if (relationshipTypeDefinitionMap.containsKey(uniqueId)) {
return Either.left(relationshipTypeDefinitionMap.get(uniqueId));
}
-
- Either<RelationshipTypeData, JanusGraphOperationStatus> relationshipTypesRes =
- janusGraphGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipType), uniqueId,
- RelationshipTypeData.class);
-
+ Either<RelationshipTypeData, JanusGraphOperationStatus> relationshipTypesRes = janusGraphGenericDao
+ .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipType), uniqueId, RelationshipTypeData.class);
if (relationshipTypesRes.isRight()) {
JanusGraphOperationStatus status = relationshipTypesRes.right().value();
logger.debug(RELATIONSHIP_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status);
return Either.right(status);
}
-
RelationshipTypeData ctData = relationshipTypesRes.left().value();
- RelationshipTypeDefinition relationshipTypeDefinition =
- new RelationshipTypeDefinition(ctData.getRelationshipTypeDataDefinition());
-
- Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesStatus =
- OperationUtils.fillProperties(uniqueId, propertyOperation, NodeTypeEnum.RelationshipType);
+ RelationshipTypeDefinition relationshipTypeDefinition = new RelationshipTypeDefinition(ctData.getRelationshipTypeDataDefinition());
+ Either<Map<String, PropertyDefinition>, JanusGraphOperationStatus> propertiesStatus = OperationUtils
+ .fillProperties(uniqueId, propertyOperation, NodeTypeEnum.RelationshipType);
if (propertiesStatus.isRight() && propertiesStatus.right().value() != JanusGraphOperationStatus.OK) {
logger.error(FAILED_TO_FETCH_PROPERTIES_OF_RELATIONSHIP_TYPE, uniqueId);
return Either.right(propertiesStatus.right().value());
}
-
if (propertiesStatus.isLeft()) {
relationshipTypeDefinition.setProperties(propertiesStatus.left().value());
}
-
fillDerivedFrom(uniqueId, relationshipTypeDefinition);
-
relationshipTypeDefinitionMap.put(relationshipTypeDefinition.getType(), relationshipTypeDefinition);
-
return Either.left(relationshipTypeDefinition);
}
- private void fillDerivedFrom(String uniqueId,
- RelationshipTypeDefinition relationshipType) {
+ private void fillDerivedFrom(String uniqueId, RelationshipTypeDefinition relationshipType) {
logger.debug("#fillDerivedFrom - fetching relationship type {} derived node", relationshipType.getType());
- derivedFromOperation.getDerivedFromChild(uniqueId, NodeTypeEnum.RelationshipType, RelationshipTypeData.class)
- .right()
- .bind(this::handleDerivedFromNotExist)
- .left()
- .map(derivedFrom -> setDerivedFrom(relationshipType, derivedFrom));
-
+ derivedFromOperation.getDerivedFromChild(uniqueId, NodeTypeEnum.RelationshipType, RelationshipTypeData.class).right()
+ .bind(this::handleDerivedFromNotExist).left().map(derivedFrom -> setDerivedFrom(relationshipType, derivedFrom));
}
private Either<RelationshipTypeData, StorageOperationStatus> handleDerivedFromNotExist(StorageOperationStatus err) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java
index 07d5387576..c9225c7295 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.operations.impl;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -30,42 +32,35 @@ import org.openecomp.sdc.be.resources.data.UserData;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.util.ValidationUtils;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
public class UniqueIdBuilder {
- private static String DOT = ".";
private static final String HEAT_PARAM_PREFIX = "heat_";
-
- public static String buildPropertyUniqueId(String resourceId, String propertyName) {
- return resourceId + DOT + propertyName;
- }
-
- static String buildHeatParameterUniqueId(String resourceId, String propertyName) {
- return resourceId + DOT + HEAT_PARAM_PREFIX + propertyName;
- }
-
- static String buildHeatParameterValueUniqueId(String resourceId, String artifactLabel, String propertyName) {
- return buildTypeUid(resourceId, artifactLabel, propertyName);
- }
-
+ private static String DOT = ".";
private static UserData userData = new UserData();
private static TagData tagData = new TagData();
private static ResourceCategoryData resCategoryData = new ResourceCategoryData();
private static ServiceCategoryData serCategoryData = new ServiceCategoryData();
-
private static Map<NodeTypeEnum, String> nodeTypeToUniqueKeyMapper = new HashMap<>();
static {
-
nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.User, userData.getUniqueIdKey());
nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.Tag, tagData.getUniqueIdKey());
nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.ResourceCategory, resCategoryData.getUniqueIdKey());
nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.ServiceCategory, serCategoryData.getUniqueIdKey());
}
+ public static String buildPropertyUniqueId(String resourceId, String propertyName) {
+ return resourceId + DOT + propertyName;
+ }
+
+ static String buildHeatParameterUniqueId(String resourceId, String propertyName) {
+ return resourceId + DOT + HEAT_PARAM_PREFIX + propertyName;
+ }
+
+ static String buildHeatParameterValueUniqueId(String resourceId, String artifactLabel, String propertyName) {
+ return buildTypeUid(resourceId, artifactLabel, propertyName);
+ }
+
/**
* find the unique id key of a node on the graph
*
@@ -73,12 +68,10 @@ public class UniqueIdBuilder {
* @return
*/
public static String getKeyByNodeType(NodeTypeEnum nodeTypeEnum) {
-
String uniqueID = nodeTypeToUniqueKeyMapper.get(nodeTypeEnum);
if (uniqueID == null) {
uniqueID = GraphPropertiesDictionary.UNIQUE_ID.getProperty();
}
-
return uniqueID;
}
@@ -106,6 +99,7 @@ public class UniqueIdBuilder {
public static String buildAttributeUid(String resourceId, String attName) {
return buildTypeUid(NodeTypeEnum.Attribute.getName(), resourceId, attName);
}
+
public static String buildRequirementUid(String resourceId, String reqName) {
return resourceId + DOT + reqName;
}
@@ -115,22 +109,18 @@ public class UniqueIdBuilder {
}
public static String buildArtifactByInterfaceUniqueId(String resourceId, String interfaceName, String operation, String artifactLabel) {
-
return resourceId + DOT + interfaceName + DOT + operation + DOT + artifactLabel;
}
public static String buildInstanceArtifactUniqueId(String parentId, String instanceId, String artifactLabel) {
-
return buildTypeUid(parentId, instanceId, artifactLabel);
}
public static String buildResourceInstanceUniuqeId(String serviceId, String resourceId, String logicalName) {
-
return buildTypeUid(serviceId, resourceId, logicalName);
}
public static String buildRelationsipInstInstanceUid(String resourceInstUid, String requirement) {
-
return generateUUID();
}
@@ -152,6 +142,7 @@ public class UniqueIdBuilder {
public static String buildCategoryUid(String categoryName, NodeTypeEnum type) {
return type.getName() + DOT + categoryName;
}
+
public static String buildComponentCategoryUid(String categoryName, VertexTypeEnum type) {
return type.getName() + DOT + ValidationUtils.normalizeCategoryName4Uniqueness(categoryName);
}
@@ -210,6 +201,5 @@ public class UniqueIdBuilder {
public static String buildGroupPropertyValueUid(String groupUniqueId, Integer index) {
return groupUniqueId + DOT + "property" + DOT + index;
-
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java
index 16073f4e3b..64bc923857 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.impl;
-import org.janusgraph.core.JanusGraphVertex;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
+import org.janusgraph.core.JanusGraphVertex;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -46,18 +53,10 @@ import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.MethodActivationStatusEnum;
-import javax.validation.constraints.NotNull;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
@org.springframework.stereotype.Component
public class UserAdminOperation {
+ private static final Logger log = Logger.getLogger(UserAdminOperation.class.getName());
private final JanusGraphGenericDao janusGraphGenericDao;
private final ToscaOperationFacade toscaOperationFacade;
@@ -66,8 +65,6 @@ public class UserAdminOperation {
this.toscaOperationFacade = toscaOperationFacade;
}
- private static final Logger log = Logger.getLogger(UserAdminOperation.class.getName());
-
public Either<User, ActionStatus> getUserData(String id, boolean inTransaction) {
return getUserData(id, true, inTransaction);
}
@@ -78,10 +75,8 @@ public class UserAdminOperation {
Wrapper<UserData> userWrapper = new Wrapper<>();
try {
validateUserExists(resultWrapper, userWrapper, id);
-
if (resultWrapper.isEmpty()) {
validateUserData(resultWrapper, userWrapper.getInnerElement(), id);
-
}
if (resultWrapper.isEmpty()) {
if (isActive) {
@@ -90,11 +85,9 @@ public class UserAdminOperation {
validateInActiveUser(resultWrapper, userWrapper.getInnerElement());
}
}
-
if (resultWrapper.isEmpty()) {
resultWrapper.setInnerElement(Either.left(convertToUser(userWrapper.getInnerElement())));
}
-
return resultWrapper.getInnerElement();
} finally {
if (!inTransaction) {
@@ -134,7 +127,6 @@ public class UserAdminOperation {
id = id.toLowerCase();
Either<UserData, JanusGraphOperationStatus> either = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class);
-
if (either.isRight()) {
resultWrapper.setInnerElement(getUserNotFoundError(id, either.right().value()));
} else {
@@ -153,7 +145,6 @@ public class UserAdminOperation {
}
log.debug("User {} saved successfully", userData.getUserId());
return convertToUser(result.left().value());
-
} finally {
if (result == null || result.isRight()) {
log.error("saveUserData - Failed");
@@ -175,9 +166,8 @@ public class UserAdminOperation {
log.error("Problem while updating User {}. Reason - {}", userData.toString(), result.right().value());
throw new StorageException(StorageOperationStatus.GENERAL_ERROR);
}
- log.debug("User {} updated successfully",userData.getUserId());
+ log.debug("User {} updated successfully", userData.getUserId());
return convertToUser(result.left().value());
-
} finally {
if (result == null || result.isRight()) {
log.error("updateUserData - Failed");
@@ -186,7 +176,6 @@ public class UserAdminOperation {
log.debug("updateUserData - end");
janusGraphGenericDao.commit();
}
-
}
}
@@ -200,7 +189,7 @@ public class UserAdminOperation {
Either<UserData, JanusGraphOperationStatus> eitherGet = janusGraphGenericDao
.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class);
if (eitherGet.isRight()) {
- log.debug("Problem while retriving user with userId {}",id);
+ log.debug("Problem while retriving user with userId {}", id);
if (eitherGet.right().value() == JanusGraphOperationStatus.NOT_FOUND) {
result = Either.right(ActionStatus.USER_NOT_FOUND);
} else {
@@ -226,24 +215,21 @@ public class UserAdminOperation {
}
private void deleteUser(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) {
- Either<UserData, JanusGraphOperationStatus> eitherDelete = janusGraphGenericDao
- .deleteNode(userData, UserData.class);
+ Either<UserData, JanusGraphOperationStatus> eitherDelete = janusGraphGenericDao.deleteNode(userData, UserData.class);
if (eitherDelete.isRight()) {
if (log.isDebugEnabled()) {
log.debug("Problem while deleting User {}. Reason - {}", userData.toString(), eitherDelete.right().value());
}
resultWrapper.setInnerElement(Either.right(ActionStatus.GENERAL_ERROR));
} else {
- log.debug("User {} deleted successfully",userData.getUserId());
+ log.debug("User {} deleted successfully", userData.getUserId());
resultWrapper.setInnerElement(Either.left(convertToUser(eitherDelete.left().value())));
}
}
private void validateUserHasNoConnections(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) {
if (resultWrapper.isEmpty()) {
-
- Either<List<Edge>, JanusGraphOperationStatus> edgesForNode = janusGraphGenericDao
- .getEdgesForNode(userData, Direction.BOTH);
+ Either<List<Edge>, JanusGraphOperationStatus> edgesForNode = janusGraphGenericDao.getEdgesForNode(userData, Direction.BOTH);
if (edgesForNode.isRight()) {
if (log.isDebugEnabled()) {
log.debug("Problem while deleting User {}. Reason - {}", userData.getUserId(), edgesForNode.right().value());
@@ -258,19 +244,16 @@ public class UserAdminOperation {
}
}
- public @NotNull List<Edge> getUserPendingTasksList(User user, List<Object> states) {
-
+ public @NotNull
+ List<Edge> getUserPendingTasksList(User user, List<Object> states) {
JanusGraphVertex userVertex = janusGraphGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), user.getUserId())
- .left()
- .on(this::handleJanusGraphError);
-
+ .left().on(this::handleJanusGraphError);
List<Edge> pendingTasks = new ArrayList<>();
for (Object state : states) {
Map<String, Object> property = new HashMap<>();
property.put(GraphPropertiesDictionary.STATE.getProperty(), state);
- List<Edge> edges = janusGraphGenericDao.getOutgoingEdgesByCriteria(userVertex, GraphEdgeLabels.STATE, property)
- .left()
- .on(this::handleJanusGraphError);
+ List<Edge> edges = janusGraphGenericDao.getOutgoingEdgesByCriteria(userVertex, GraphEdgeLabels.STATE, property).left()
+ .on(this::handleJanusGraphError);
for (Edge edge : edges) {
Vertex vertex = edge.inVertex();
if (!isComponentDeleted(vertex)) {
@@ -282,7 +265,8 @@ public class UserAdminOperation {
return pendingTasks;
}
- public @NotNull List<Component> getUserActiveComponents(User user, List<Object> states) {
+ public @NotNull
+ List<Component> getUserActiveComponents(User user, List<Object> states) {
List<Component> components = new ArrayList<>();
List<Edge> edges = getUserPendingTasksList(user, states);
for (Edge edge : edges) {
@@ -316,7 +300,8 @@ public class UserAdminOperation {
Object resourceUuid = edge.inVertex().property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value();
Object componentName = edge.inVertex().property(GraphPropertyEnum.NAME.getProperty()).value();
Object componentState = edge.inVertex().property(GraphPropertyEnum.STATE.getProperty()).value();
- log.debug("The user userId = {} is working on the component name = {} uid = {} in state {}", user.getUserId(), componentName, resourceUuid, componentState);
+ log.debug("The user userId = {} is working on the component name = {} uid = {} in state {}", user.getUserId(), componentName,
+ resourceUuid, componentState);
}
}
}
@@ -330,10 +315,8 @@ public class UserAdminOperation {
if (status != null && !status.isEmpty()) {
propertiesToMatch.put(GraphPropertiesDictionary.USER_STATUS.getProperty(), status);
}
-
Either<List<UserData>, JanusGraphOperationStatus> userNodes = janusGraphGenericDao
.getByCriteria(NodeTypeEnum.User, propertiesToMatch, UserData.class);
-
janusGraphGenericDao.commit();
return convertToUsers(role, userNodes);
} finally {
@@ -342,7 +325,6 @@ public class UserAdminOperation {
}
private Either<List<User>, ActionStatus> convertToUsers(String role, Either<List<UserData>, JanusGraphOperationStatus> userNodes) {
-
if (userNodes.isRight()) {
// in case of NOT_FOUND from JanusGraph return empty list
JanusGraphOperationStatus tos = userNodes.right().value();
@@ -377,7 +359,7 @@ public class UserAdminOperation {
return Either.right(ActionStatus.USER_NOT_FOUND);
} else {
log.debug("Problem get User with userId {}. Reason - {}", uid, status);
- return Either.right(ActionStatus.GENERAL_ERROR);
+ return Either.right(ActionStatus.GENERAL_ERROR);
}
}
@@ -390,6 +372,7 @@ public class UserAdminOperation {
user.setRole(userData.getRole());
user.setLastLoginTime(userData.getLastLoginTime());
// Support backward compatibility - user status may not exist in old
+
// users
Either<UserStatusEnum, MethodActivationStatusEnum> either = UserStatusEnum.findByName(userData.getStatus());
user.setStatus(either.isLeft() ? either.left().value() : UserStatusEnum.ACTIVE);
@@ -407,5 +390,4 @@ public class UserAdminOperation {
userData.setLastLoginTime(user.getLastLoginTime());
return userData;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java
index 9621f9e401..89ac1ef6bc 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java
@@ -8,9 +8,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,9 +18,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.operations.utils;
+import fj.data.Either;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
@@ -29,8 +29,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 fj.data.Either;
-
public class ComponentValidationUtils {
private static final Logger log = Logger.getLogger(ComponentValidationUtils.class.getName());
@@ -57,18 +55,14 @@ public class ComponentValidationUtils {
return true;
}
- public static boolean canWorkOnComponent(String componentId,
- ToscaOperationFacade toscaOperationFacade, String userId) {
-
- Either<Component, StorageOperationStatus> getResourceResult =
- toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseMetadata);
-
+ public static boolean canWorkOnComponent(String componentId, ToscaOperationFacade toscaOperationFacade, String userId) {
+ Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade
+ .getToscaElement(componentId, JsonParseFlagEnum.ParseMetadata);
if (getResourceResult.isRight()) {
log.debug("Failed to retrieve component, component id {}", componentId);
return false;
}
Component component = getResourceResult.left().value();
-
return canWorkOnComponent(component, userId);
}
@@ -76,20 +70,17 @@ public class ComponentValidationUtils {
return canWorkOnComponent(component.getLifecycleState(), component.getLastUpdaterUserId(), userId);
}
- private static boolean canWorkOnComponent(LifecycleStateEnum lifecycleState,
- String lastUpdaterUserId, String userId) {
+ private static boolean canWorkOnComponent(LifecycleStateEnum lifecycleState, String lastUpdaterUserId, String userId) {
// verify resource is checked-out
if (lifecycleState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
log.debug("resource is not checked-out");
return false;
}
-
// verify userId is not null
if (userId == null) {
log.debug("current user userId is null");
return false;
}
-
// verify resource last update user is the current user
if (!userId.equals(lastUpdaterUserId)) {
log.debug("resource last updater userId is not {}", userId);
@@ -97,5 +88,4 @@ public class ComponentValidationUtils {
}
return true;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java
index 2f1372d8bd..ec7ca43155 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,59 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca;
-import org.openecomp.sdc.be.model.tosca.converters.*;
-import org.openecomp.sdc.be.model.tosca.validators.*;
+import org.openecomp.sdc.be.model.tosca.converters.BooleanConverter;
+import org.openecomp.sdc.be.model.tosca.converters.DefaultConverter;
+import org.openecomp.sdc.be.model.tosca.converters.FloatConverter;
+import org.openecomp.sdc.be.model.tosca.converters.IntegerConverter;
+import org.openecomp.sdc.be.model.tosca.converters.JsonConverter;
+import org.openecomp.sdc.be.model.tosca.converters.ListConverter;
+import org.openecomp.sdc.be.model.tosca.converters.MapConverter;
+import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
+import org.openecomp.sdc.be.model.tosca.converters.StringConvertor;
+import org.openecomp.sdc.be.model.tosca.converters.ToscaBooleanConverter;
+import org.openecomp.sdc.be.model.tosca.converters.ToscaFloatConverter;
+import org.openecomp.sdc.be.model.tosca.converters.ToscaJsonValueConverter;
+import org.openecomp.sdc.be.model.tosca.converters.ToscaListValueConverter;
+import org.openecomp.sdc.be.model.tosca.converters.ToscaMapValueConverter;
+import org.openecomp.sdc.be.model.tosca.converters.ToscaStringConvertor;
+import org.openecomp.sdc.be.model.tosca.converters.ToscaValueConverter;
+import org.openecomp.sdc.be.model.tosca.converters.ToscaValueDefaultConverter;
+import org.openecomp.sdc.be.model.tosca.validators.BooleanValidator;
+import org.openecomp.sdc.be.model.tosca.validators.FloatValidator;
+import org.openecomp.sdc.be.model.tosca.validators.IntegerValidator;
+import org.openecomp.sdc.be.model.tosca.validators.JsonValidator;
+import org.openecomp.sdc.be.model.tosca.validators.KeyValidator;
+import org.openecomp.sdc.be.model.tosca.validators.ListValidator;
+import org.openecomp.sdc.be.model.tosca.validators.MapValidator;
+import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
+import org.openecomp.sdc.be.model.tosca.validators.StringValidator;
/**
* The primitive type that TOSCA YAML supports.
- *
+ *
* @author esofer
*/
public enum ToscaPropertyType {
-
+ // @formatter:off
ROOT("tosca.datatypes.Root", null, null, null, true),
-
STRING("string", StringValidator.getInstance(), StringConvertor.getInstance(), ToscaStringConvertor.getInstance()),
-
BOOLEAN("boolean", BooleanValidator.getInstance(), ToscaBooleanConverter.getInstance(), BooleanConverter.getInstance()),
-
FLOAT("float", FloatValidator.getInstance(), ToscaFloatConverter.getInstance(), FloatConverter.getInstance()),
-
INTEGER("integer", IntegerValidator.getInstance(), DefaultConverter.getInstance(), IntegerConverter.getInstance()),
-
SCALAR_UNIT("scalar-unit", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
-
SCALAR_UNIT_SIZE("scalar-unit.size", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
-
SCALAR_UNIT_TIME("scalar-unit.time", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
-
SCALAR_UNIT_FREQUENCY("scalar-unit.frequency", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
-
RANGE("range", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
-
TIMESTAMP("timestamp", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
-
MAP("map", MapValidator.getInstance(), MapConverter.getInstance(), ToscaMapValueConverter.getInstance()),
-
LIST("list", ListValidator.getInstance(), ListConverter.getInstance(), ToscaListValueConverter.getInstance()),
-
VERSION("version", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()),
-
KEY("key", KeyValidator.getInstance(), StringConvertor.getInstance(), ToscaValueDefaultConverter.getInstance()),
-
JSON("json", JsonValidator.getInstance(), JsonConverter.getInstance(), ToscaJsonValueConverter.getInstance());
+ // @formatter:on
private String type;
private PropertyTypeValidator validator;
@@ -75,36 +84,16 @@ public enum ToscaPropertyType {
this.valueConverter = valueConverter;
}
- ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, ToscaValueConverter valueConverter, boolean isAbstract) {
+ ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, ToscaValueConverter valueConverter,
+ boolean isAbstract) {
this(type, validator, converter, valueConverter);
this.isAbstract = isAbstract;
}
- public String getType() {
- return type;
- }
-
- public PropertyTypeValidator getValidator() {
- return validator;
- }
-
- public PropertyValueConverter getConverter() {
- return converter;
- }
-
- public boolean isAbstract() {
- return isAbstract;
- }
-
- public ToscaValueConverter getValueConverter() {
- return valueConverter;
- }
-
public static ToscaPropertyType isValidType(String typeName) {
if (typeName == null) {
return null;
}
-
for (ToscaPropertyType type : ToscaPropertyType.values()) {
if (type.getType().equals(typeName)) {
return type;
@@ -114,34 +103,47 @@ public enum ToscaPropertyType {
}
public static boolean isScalarType(String dataTypeName) {
-
ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
-
return isPrimitiveToscaType != null && !isPrimitiveToscaType.isAbstract();
-
}
public static boolean isPrimitiveType(String dataTypeName) {
-
- if (ToscaPropertyType.MAP.getType().equals(dataTypeName) || ToscaPropertyType.LIST.getType().equals(dataTypeName)){
+ if (ToscaPropertyType.MAP.getType().equals(dataTypeName) || ToscaPropertyType.LIST.getType().equals(dataTypeName)) {
return false;
}
- if(isScalarType(dataTypeName)){
+ if (isScalarType(dataTypeName)) {
return true;
}
return false;
}
public static ToscaPropertyType getTypeIfScalar(String dataTypeName) {
-
ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
-
if (isPrimitiveToscaType != null && !isPrimitiveToscaType.isAbstract()) {
return isPrimitiveToscaType;
} else {
return null;
}
+ }
+ public String getType() {
+ return type;
+ }
+
+ public PropertyTypeValidator getValidator() {
+ return validator;
+ }
+
+ public PropertyValueConverter getConverter() {
+ return converter;
+ }
+
+ public boolean isAbstract() {
+ return isAbstract;
+ }
+
+ public ToscaValueConverter getValueConverter() {
+ return valueConverter;
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java
index 034f6fab92..a880db0c14 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,28 +17,26 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
-import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
-
import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException;
/**
* The primitive type that TOSCA YAML supports.
- *
+ *
* @author mkv
*/
public enum ToscaType {
+ // @formatter:off
STRING("string"),
INTEGER("integer"),
FLOAT("float"),
@@ -51,89 +49,106 @@ public enum ToscaType {
SCALAR_UNIT_SIZE("scalar-unit.size"),
SCALAR_UNIT_TIME("scalar-unit.time"),
SCALAR_UNIT_FREQUENCY("scalar-unit.frequency");
+ // @formatter:on
+
+ private String type;
+
+ ToscaType(String type) {
+ this.type = type;
+ }
+
+ public static ToscaType getToscaType(String typeName) {
+ if (typeName == null) {
+ return null;
+ }
+ for (ToscaType type : ToscaType.values()) {
+ if (type.getType().equals(typeName)) {
+ return type;
+ }
+ }
+ return null;
+ }
+
+ public static boolean isPrimitiveType(String dataTypeName) {
+ if (!ToscaPropertyType.MAP.getType().equals(dataTypeName) && !ToscaPropertyType.LIST.getType().equals(dataTypeName)) {
+ return isValidType(dataTypeName) != null;
+ }
+ return false;
+ }
- private String type;
-
- ToscaType(String type) {
- this.type = type;
- }
-
- public String getType() {
- return type;
- }
-
- public static ToscaType getToscaType(String typeName) {
- if (typeName == null) {
- return null;
- }
-
- for (ToscaType type : ToscaType.values()) {
- if (type.getType().equals(typeName)) {
- return type;
- }
- }
- return null;
- }
-
- public boolean isValidValue(String value) {
- switch (this) {
- case BOOLEAN:
- return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false");
- case FLOAT:
- return isFloat(value);
- case INTEGER:
- return isInteger(value);
- case STRING:
- case SCALAR_UNIT:
- case SCALAR_UNIT_SIZE:
- case SCALAR_UNIT_TIME:
- case SCALAR_UNIT_FREQUENCY:
- return true;
- case TIMESTAMP:
- try {
- new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US).parse(value);
- return true;
- } catch (ParseException e) {
- return false;
- }
- case VERSION:
- return VersionUtil.isValid(value);
- case LIST:
- return isList(value);
- case MAP:
- return isMap(value);
- default:
- return false;
- }
- }
-
- private boolean isList(String value) {
- ObjectMapper objectMapper = new ObjectMapper();
- try {
- objectMapper.readValue(value,
- new TypeReference<List<Object>>() {
- });
-
- } catch (IOException e) {
- return false;
- }
-
- return true;
- }
-
- private boolean isMap(String value) {
- ObjectMapper objectMapper = new ObjectMapper();
- try {
- objectMapper.readValue(value,
- new TypeReference<Map<String, Object>>() {
- });
-
- } catch (IOException e) {
- return false;
- }
-
- return true;
- }
+ public static ToscaType isValidType(String typeName) {
+ if (typeName == null) {
+ return null;
+ }
+ for (ToscaType type : ToscaType.values()) {
+ if (type.getType().equals(typeName)) {
+ return type;
+ }
+ }
+ return null;
+ }
+
+ public static boolean isCollectionType(String type) {
+ return ToscaPropertyType.MAP.getType().equals(type) || ToscaPropertyType.LIST.getType().equals(type);
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public boolean isValidValue(String value) {
+ switch (this) {
+ case BOOLEAN:
+ return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false");
+ case FLOAT:
+ return isFloat(value);
+ case INTEGER:
+ return isInteger(value);
+ case STRING:
+ case SCALAR_UNIT:
+ case SCALAR_UNIT_SIZE:
+ case SCALAR_UNIT_TIME:
+ case SCALAR_UNIT_FREQUENCY:
+ return true;
+ case TIMESTAMP:
+ try {
+ new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US).parse(value);
+ return true;
+ } catch (ParseException e) {
+ return false;
+ }
+ case VERSION:
+ return VersionUtil.isValid(value);
+ case LIST:
+ return isList(value);
+ case MAP:
+ return isMap(value);
+ default:
+ return false;
+ }
+ }
+
+ private boolean isList(String value) {
+ ObjectMapper objectMapper = new ObjectMapper();
+ try {
+ objectMapper.readValue(value, new TypeReference<List<Object>>() {
+ });
+ } catch (IOException e) {
+ return false;
+ }
+ return true;
+ }
+
+ private boolean isMap(String value) {
+ ObjectMapper objectMapper = new ObjectMapper();
+ try {
+ objectMapper.readValue(value, new TypeReference<Map<String, Object>>() {
+ });
+ } catch (IOException e) {
+ return false;
+ }
+ return true;
+ }
private boolean isFloat(String value) {
try {
@@ -153,78 +168,49 @@ public enum ToscaType {
return true;
}
- public Object convert(String value) {
- switch (this) {
- case STRING:
- case SCALAR_UNIT:
- case SCALAR_UNIT_SIZE:
- case SCALAR_UNIT_TIME:
- case SCALAR_UNIT_FREQUENCY:
- return value;
- case BOOLEAN:
- return Boolean.valueOf(value);
- case FLOAT:
- return Float.valueOf(value);
- case INTEGER:
- return Long.valueOf(value);
- case TIMESTAMP:
- try {
- return new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US).parse(value);
- } catch (ParseException e) {
- throw new IllegalArgumentException("Value must be a valid timestamp", e);
- }
- case VERSION:
- return VersionUtil.parseVersion(value);
- case LIST:
- try {
- return ConstraintUtil.parseToCollection(value, new TypeReference<List<Object>>() {});
- } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
- throw new IllegalArgumentException("Value must be a valid List", e);
- }
- case MAP:
- try {
- return ConstraintUtil.parseToCollection(value, new TypeReference<Map<String, Object>>() {});
- } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
- throw new IllegalArgumentException("Value must be a valid Map", e);
- }
- default:
- return null;
- }
- }
-
- public static boolean isPrimitiveType(String dataTypeName) {
-
- if (!ToscaPropertyType.MAP.getType().equals(dataTypeName) && !ToscaPropertyType.LIST.getType()
- .equals(dataTypeName)) {
-
- return isValidType(dataTypeName) != null;
- }
-
- return false;
- }
-
- public static ToscaType isValidType(String typeName) {
- if (typeName == null) {
- return null;
- }
-
- for (ToscaType type : ToscaType.values()) {
- if (type.getType().equals(typeName)) {
- return type;
- }
- }
- return null;
- }
-
- @Override
- public String toString() {
- return name().toLowerCase();
+ public Object convert(String value) {
+ switch (this) {
+ case STRING:
+ case SCALAR_UNIT:
+ case SCALAR_UNIT_SIZE:
+ case SCALAR_UNIT_TIME:
+ case SCALAR_UNIT_FREQUENCY:
+ return value;
+ case BOOLEAN:
+ return Boolean.valueOf(value);
+ case FLOAT:
+ return Float.valueOf(value);
+ case INTEGER:
+ return Long.valueOf(value);
+ case TIMESTAMP:
+ try {
+ return new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US).parse(value);
+ } catch (ParseException e) {
+ throw new IllegalArgumentException("Value must be a valid timestamp", e);
+ }
+ case VERSION:
+ return VersionUtil.parseVersion(value);
+ case LIST:
+ try {
+ return ConstraintUtil.parseToCollection(value, new TypeReference<List<Object>>() {
+ });
+ } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
+ throw new IllegalArgumentException("Value must be a valid List", e);
+ }
+ case MAP:
+ try {
+ return ConstraintUtil.parseToCollection(value, new TypeReference<Map<String, Object>>() {
+ });
+ } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
+ throw new IllegalArgumentException("Value must be a valid Map", e);
+ }
+ default:
+ return null;
+ }
}
- public static boolean isCollectionType(String type) {
- return ToscaPropertyType.MAP.getType().equals(type)
- || ToscaPropertyType.LIST.getType().equals(type);
+ @Override
+ public String toString() {
+ return name().toLowerCase();
}
-
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/VersionUtil.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/VersionUtil.java
index 41b7a2e342..67173c2234 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/VersionUtil.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/VersionUtil.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,35 +17,32 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca;
+import java.util.regex.Pattern;
import org.openecomp.sdc.be.model.tosca.version.ApplicationVersionException;
import org.openecomp.sdc.be.model.tosca.version.Version;
-import java.util.regex.Pattern;
-
public final class VersionUtil {
- /** Utility class should not have public constructor. */
- private VersionUtil() {
- }
-
/**
- * The version must begin with a bloc of numbers, and then it can have one
- * or more bloc of numbers separated by '.' and then it can have alpha
+ * The version must begin with a bloc of numbers, and then it can have one or more bloc of numbers separated by '.' and then it can have alpha
* numeric bloc separated by '.' or '-'
*/
public static final Pattern VERSION_PATTERN = Pattern.compile("\\d+(?:\\.\\d+)*(?:[\\.-]\\p{Alnum}+)*");
private static final String SNAPSHOT_IDENTIFIER = "SNAPSHOT";
/**
+ * Utility class should not have public constructor.
+ */
+ private VersionUtil() {
+ }
+
+ /**
* Check if a version is a SNAPSHOT (development) version.
*
- * @param version
- * The actual version string.
- * @return True if the version is a SNAPSHOT version, false if not (RELEASE
- * version).
+ * @param version The actual version string.
+ * @return True if the version is a SNAPSHOT version, false if not (RELEASE version).
*/
public static boolean isSnapshot(String version) {
return version.toUpperCase().contains(SNAPSHOT_IDENTIFIER);
@@ -54,8 +51,7 @@ public final class VersionUtil {
/**
* Check if a version is valid
*
- * @param version
- * version string to parse
+ * @param version version string to parse
* @return true if it's following the defined version pattern
*/
public static boolean isValid(String version) {
@@ -65,17 +61,13 @@ public final class VersionUtil {
/**
* Parse the version's text to produce a comparable version object
*
- * @param version
- * version text to parse
+ * @param version version text to parse
* @return a comparable version object
- * @throws ApplicationVersionException
- * if the version text is not following the defined version
- * pattern
+ * @throws ApplicationVersionException if the version text is not following the defined version pattern
*/
public static Version parseVersion(String version) {
if (!isValid(version)) {
- throw new ApplicationVersionException(
- "This version is not valid [" + version + "] as it does not match [" + VERSION_PATTERN + "]");
+ throw new ApplicationVersionException("This version is not valid [" + version + "] as it does not match [" + VERSION_PATTERN + "]");
} else {
return new Version(version);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractComparablePropertyConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractComparablePropertyConstraint.java
index 1611356cc1..42fb1eb00c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractComparablePropertyConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractComparablePropertyConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints;
import org.openecomp.sdc.be.model.tosca.ToscaType;
@@ -33,9 +32,9 @@ public abstract class AbstractComparablePropertyConstraint extends AbstractPrope
return comparable;
}
- protected void initialize(String rawTextValue, ToscaType propertyType)
- throws ConstraintValueDoNotMatchPropertyTypeException {
+ protected void initialize(String rawTextValue, ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException {
// Perform verification that the property type is supported for
+
// comparison
ConstraintUtil.checkComparableType(propertyType);
// Check if the text value is valid for the property type
@@ -45,7 +44,7 @@ public abstract class AbstractComparablePropertyConstraint extends AbstractPrope
} else {
// Invalid value throw exception
throw new ConstraintValueDoNotMatchPropertyTypeException(
- "The value [" + rawTextValue + "] is not valid for the type [" + propertyType + "]");
+ "The value [" + rawTextValue + "] is not valid for the type [" + propertyType + "]");
}
}
@@ -57,8 +56,9 @@ public abstract class AbstractComparablePropertyConstraint extends AbstractPrope
throw new ConstraintViolationException("Value to check is null");
}
if (!(comparable.getClass().isAssignableFrom(propertyValue.getClass()))) {
- throw new ConstraintViolationException("Value to check is not comparable to reference type, value type ["
- + propertyValue.getClass() + "], reference type [" + comparable.getClass() + "]");
+ throw new ConstraintViolationException(
+ "Value to check is not comparable to reference type, value type [" + propertyValue.getClass() + "], reference type [" + comparable
+ .getClass() + "]");
}
doValidate(propertyValue);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractPropertyConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractPropertyConstraint.java
index 041a86d283..4b4c0a66d0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractPropertyConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractPropertyConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints;
import java.util.Arrays;
-
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException;
@@ -31,28 +29,22 @@ import org.openecomp.sdc.be.model.tosca.version.ApplicationVersionException;
public abstract class AbstractPropertyConstraint implements PropertyConstraint {
- private static final String INVALID_VALUE_ERROR_MESSAGE =
- "Unsupported value provided for %s property supported value type is %s.";
+ private static final String INVALID_VALUE_ERROR_MESSAGE = "Unsupported value provided for %s property supported value type is %s.";
@Override
public void validate(ToscaType toscaType, String propertyTextValue) throws ConstraintViolationException {
try {
validate(toscaType.convert(propertyTextValue));
} catch (IllegalArgumentException | ApplicationVersionException e) {
- throw new ConstraintViolationException(
- "String value [" + propertyTextValue + "] is not valid for type [" + toscaType + "]", e);
+ throw new ConstraintViolationException("String value [" + propertyTextValue + "] is not valid for type [" + toscaType + "]", e);
}
}
- public String getErrorMessage(ToscaType toscaType,
- ConstraintFunctionalException e,
- String propertyName,
- String errorMessage,
- String... propertyValue) {
+ public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName, String errorMessage,
+ String... propertyValue) {
if (e instanceof ConstraintViolationException) {
return String.format(errorMessage, propertyName, Arrays.toString(propertyValue));
}
-
return String.format(INVALID_VALUE_ERROR_MESSAGE, propertyName, toscaType.getType());
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractStringPropertyConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractStringPropertyConstraint.java
index 8f54c68484..668b9839af 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractStringPropertyConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/AbstractStringPropertyConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints;
import org.openecomp.sdc.be.model.tosca.ToscaType;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java
index bce2a41b98..3647bd67d0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,35 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints;
import java.util.Arrays;
import java.util.List;
public enum ConstraintType {
-
- EQUAL("equal", "equal"),
-
+ // @formatter:off
+ EQUAL("equal", "equal"),
IN_RANGE("inRange", "in_range"),
-
GREATER_THAN("greaterThan", "greater_than"),
-
GREATER_OR_EQUAL("greaterOrEqual", "greater_or_equal"),
-
LESS_OR_EQUAL("lessOrEqual", "less_or_equal"),
-
LENGTH("length", "length"),
-
MIN_LENGTH("minLength", "min_length"),
-
MAX_LENGTH("maxLength", "max_length"),
-
VALID_VALUES("validValues", "valid_values"),
-
LESS_THAN("lessThan", "less_than"),
-
SCHEMA("schema", "schema");
+ // @formatter:on
List<String> types;
@@ -53,10 +43,6 @@ public enum ConstraintType {
this.types = Arrays.asList(types);
}
- public List<String> getTypes() {
- return types;
- }
-
public static ConstraintType getByType(String type) {
for (ConstraintType inst : ConstraintType.values()) {
if (inst.getTypes().contains(type)) {
@@ -65,4 +51,8 @@ public enum ConstraintType {
}
return null;
}
+
+ public List<String> getTypes() {
+ return types;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintUtil.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintUtil.java
index 188ad1b5c7..74a9359f2a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintUtil.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintUtil.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints;
import com.fasterxml.jackson.core.type.TypeReference;
@@ -27,7 +26,6 @@ import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
-
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException;
import org.slf4j.Logger;
@@ -44,93 +42,65 @@ public final class ConstraintUtil {
}
/**
- * Validates that the {@link ToscaType} specified is a
- * {@link ToscaType#STRING}.
+ * Validates that the {@link ToscaType} specified is a {@link ToscaType#STRING}.
*
- * @param propertyType
- * The property tosca type.
- * @throws ConstraintValueDoNotMatchPropertyTypeException
- * In case the type is not {@link ToscaType#STRING}.
+ * @param propertyType The property tosca type.
+ * @throws ConstraintValueDoNotMatchPropertyTypeException In case the type is not {@link ToscaType#STRING}.
*/
public static void checkStringType(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException {
if (ToscaType.STRING != propertyType) {
- throw new ConstraintValueDoNotMatchPropertyTypeException(
- "Invalid property type <" + propertyType.toString() + ">");
+ throw new ConstraintValueDoNotMatchPropertyTypeException("Invalid property type <" + propertyType.toString() + ">");
}
}
/**
* Verify that the given tosca type is supported for comparison
*
- * @param propertyType
- * the tosca type to check
- * @throws ConstraintValueDoNotMatchPropertyTypeException
- * if the property type cannot be compared
+ * @param propertyType the tosca type to check
+ * @throws ConstraintValueDoNotMatchPropertyTypeException if the property type cannot be compared
*/
- public static void checkComparableType(ToscaType propertyType)
- throws ConstraintValueDoNotMatchPropertyTypeException {
+ public static void checkComparableType(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException {
// The validity of the value is already assured by us with our
+
// ToscaType.convert() method
+
// here we just want to check that the constraint is not used on
+
// unsupported type as boolean
switch (propertyType) {
- case FLOAT:
- case INTEGER:
- case TIMESTAMP:
- case VERSION:
- break;
- case STRING:
- case BOOLEAN:
- throw new ConstraintValueDoNotMatchPropertyTypeException(
- "Constraint is invalid for property type <" + propertyType.toString() + ">");
- default:
- throw new ConstraintValueDoNotMatchPropertyTypeException(
- "Invalid property type <" + propertyType.toString() + ">");
+ case FLOAT:
+ case INTEGER:
+ case TIMESTAMP:
+ case VERSION:
+ break;
+ case STRING:
+ case BOOLEAN:
+ throw new ConstraintValueDoNotMatchPropertyTypeException("Constraint is invalid for property type <" + propertyType.toString() + ">");
+ default:
+ throw new ConstraintValueDoNotMatchPropertyTypeException("Invalid property type <" + propertyType.toString() + ">");
}
}
/**
- * Convert a string value following its type throw exception if it cannot be
- * converted to a comparable
+ * Convert a string value following its type throw exception if it cannot be converted to a comparable
*
- * @param propertyType
- * the type of the property
- * @param value
- * the value to convert
+ * @param propertyType the type of the property
+ * @param value the value to convert
* @return the converted comparable
- * @throws ConstraintValueDoNotMatchPropertyTypeException
- * if the converted value is not a comparable
+ * @throws ConstraintValueDoNotMatchPropertyTypeException if the converted value is not a comparable
*/
@SuppressWarnings("rawtypes")
public static Comparable convertToComparable(ToscaType propertyType, String value) {
Object comparableObj = propertyType.convert(value);
if (!(comparableObj instanceof Comparable)) {
- throw new IllegalArgumentException(
- "Try to convert a value of a type which is not comparable [" + propertyType + "] to Comparable");
+ throw new IllegalArgumentException("Try to convert a value of a type which is not comparable [" + propertyType + "] to Comparable");
} else {
return (Comparable) comparableObj;
}
}
- public static class ConstraintInformation {
- public ConstraintInformation(String name, Object reference, String value, String type) {
-
- this.name = name;
- this.reference = reference;
- this.value = value;
- this.type = type;
-
- }
-
- private String name;
- private Object reference;
- private String value;
- private String type;
- }
-
public static ConstraintInformation getConstraintInformation(Object constraint) throws IntrospectionException {
- PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(constraint.getClass())
- .getPropertyDescriptors();
+ PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(constraint.getClass()).getPropertyDescriptors();
PropertyDescriptor firstDescriptor = null;
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) {
@@ -142,15 +112,13 @@ public final class ConstraintUtil {
throw new IntrospectionException("Cannot find constraint name");
}
try {
- return new ConstraintInformation(firstDescriptor.getName(),
- firstDescriptor.getReadMethod().invoke(constraint), null, null);
+ return new ConstraintInformation(firstDescriptor.getName(), firstDescriptor.getReadMethod().invoke(constraint), null, null);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new IntrospectionException("Cannot retrieve constraint reference " + e.getMessage());
}
}
- public static <T> T parseToCollection(String value, TypeReference<T> typeReference)
- throws ConstraintValueDoNotMatchPropertyTypeException {
+ public static <T> T parseToCollection(String value, TypeReference<T> typeReference) throws ConstraintValueDoNotMatchPropertyTypeException {
T objectMap;
ObjectMapper objectMapper = new ObjectMapper();
try {
@@ -159,7 +127,21 @@ public final class ConstraintUtil {
logger.error(e.getMessage(), e);
throw new ConstraintValueDoNotMatchPropertyTypeException("The value [" + value + "] is not valid");
}
-
return objectMap;
}
+
+ public static class ConstraintInformation {
+
+ private String name;
+ private Object reference;
+ private String value;
+ private String type;
+
+ public ConstraintInformation(String name, Object reference, String value, String type) {
+ this.name = name;
+ this.reference = reference;
+ this.value = value;
+ this.type = type;
+ }
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java
index 01d9d3b252..4b62b12897 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java
@@ -17,45 +17,42 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints;
-import org.openecomp.sdc.be.model.PropertyConstraint;
import java.io.Serializable;
+import javax.validation.constraints.NotNull;
+import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
-import javax.validation.constraints.NotNull;
-
@SuppressWarnings("serial")
public class EqualConstraint extends AbstractPropertyConstraint implements Serializable {
- @NotNull
- private String constraintValue;
+ @NotNull
+ private String constraintValue;
private Object typed;
- public EqualConstraint(String constraintValue) {
- super();
- this.constraintValue = constraintValue;
- }
+ public EqualConstraint(String constraintValue) {
+ super();
+ this.constraintValue = constraintValue;
+ }
- public String getConstraintValue() {
- return constraintValue;
- }
+ public String getConstraintValue() {
+ return constraintValue;
+ }
- @Override
- public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException {
- if (propertyType.isValidValue(constraintValue)) {
- typed = propertyType.convert(constraintValue);
- } else {
+ @Override
+ public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException {
+ if (propertyType.isValidValue(constraintValue)) {
+ typed = propertyType.convert(constraintValue);
+ } else {
throw new ConstraintValueDoNotMatchPropertyTypeException(
- "constraintValue constraint has invalid value <" + constraintValue
- + "> property type is <" + propertyType.toString() + ">");
- }
- }
+ "constraintValue constraint has invalid value <" + constraintValue + "> property type is <" + propertyType.toString() + ">");
+ }
+ }
@Override
public void validate(Object propertyValue) throws ConstraintViolationException {
@@ -79,16 +76,15 @@ public class EqualConstraint extends AbstractPropertyConstraint implements Seria
@Override
public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException {
-
}
- private void fail(Object propertyValue) throws ConstraintViolationException {
- throw new ConstraintViolationException("Equal constraint violation, the reference is <" + constraintValue
- + "> but the value to compare is <" + propertyValue + ">");
- }
+ private void fail(Object propertyValue) throws ConstraintViolationException {
+ throw new ConstraintViolationException(
+ "Equal constraint violation, the reference is <" + constraintValue + "> but the value to compare is <" + propertyValue + ">");
+ }
- @Override
- public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) {
- return getErrorMessage(toscaType, e, propertyName, "%s property value must be %s", constraintValue);
+ @Override
+ public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) {
+ return getErrorMessage(toscaType, e, propertyName, "%s property value must be %s", constraintValue);
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java
index cd132502ac..dc50d7d549 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints;
+import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@@ -30,8 +30,6 @@ import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoN
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
-import javax.validation.constraints.NotNull;
-
@Getter
@Setter
@AllArgsConstructor
@@ -52,7 +50,6 @@ public class GreaterOrEqualConstraint extends AbstractComparablePropertyConstrai
@Override
public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException {
-
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java
index e5f0779ed1..0b76e97967 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints;
+import javax.validation.constraints.NotNull;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException;
@@ -27,8 +27,6 @@ import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoN
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
-import javax.validation.constraints.NotNull;
-
public class GreaterThanConstraint extends AbstractComparablePropertyConstraint {
@NotNull
@@ -50,7 +48,6 @@ public class GreaterThanConstraint extends AbstractComparablePropertyConstraint
@Override
public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException {
-
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java
index f9b27d4953..bfb1b75a5c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints;
import com.google.common.collect.Lists;
-import org.openecomp.sdc.be.model.PropertyConstraint;
import java.util.List;
+import javax.validation.constraints.NotNull;
+import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
-import javax.validation.constraints.NotNull;
-
public class InRangeConstraint extends AbstractPropertyConstraint {
private List<String> inRange;
-
private Comparable min;
private Comparable max;
@@ -42,11 +39,13 @@ public class InRangeConstraint extends AbstractPropertyConstraint {
this.inRange = inRange;
}
- public InRangeConstraint() { }
+ public InRangeConstraint() {
+ }
@Override
public void initialize(ToscaType propertyType) throws ConstraintValueDoNotMatchPropertyTypeException {
// Perform verification that the property type is supported for
+
// comparison
ConstraintUtil.checkComparableType(propertyType);
if (inRange == null || inRange.size() != 2) {
@@ -55,12 +54,12 @@ public class InRangeConstraint extends AbstractPropertyConstraint {
String minRawText = inRange.get(0);
String maxRawText = inRange.get(1);
if (!propertyType.isValidValue(minRawText)) {
- throw new ConstraintValueDoNotMatchPropertyTypeException("Invalid min value for in range constraint ["
- + minRawText + "] as it does not follow the property type [" + propertyType + "]");
+ throw new ConstraintValueDoNotMatchPropertyTypeException(
+ "Invalid min value for in range constraint [" + minRawText + "] as it does not follow the property type [" + propertyType + "]");
}
if (!propertyType.isValidValue(maxRawText)) {
- throw new ConstraintValueDoNotMatchPropertyTypeException("Invalid max value for in range constraint ["
- + maxRawText + "] as it does not follow the property type [" + propertyType + "]");
+ throw new ConstraintValueDoNotMatchPropertyTypeException(
+ "Invalid max value for in range constraint [" + maxRawText + "] as it does not follow the property type [" + propertyType + "]");
}
min = ConstraintUtil.convertToComparable(propertyType, minRawText);
max = ConstraintUtil.convertToComparable(propertyType, maxRawText);
@@ -72,8 +71,8 @@ public class InRangeConstraint extends AbstractPropertyConstraint {
throw new ConstraintViolationException("Value to check is null");
}
if (!(min.getClass().isAssignableFrom(propertyValue.getClass()))) {
- throw new ConstraintViolationException("Value to check is not comparable to range type, value type ["
- + propertyValue.getClass() + "], range type [" + min.getClass() + "]");
+ throw new ConstraintViolationException(
+ "Value to check is not comparable to range type, value type [" + propertyValue.getClass() + "], range type [" + min.getClass() + "]");
}
if (min.compareTo(propertyValue) > 0 || max.compareTo(propertyValue) < 0) {
throw new ConstraintViolationException("The value [" + propertyValue + "] is out of range " + inRange);
@@ -87,7 +86,6 @@ public class InRangeConstraint extends AbstractPropertyConstraint {
@Override
public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException {
-
}
@NotNull
@@ -126,8 +124,7 @@ public class InRangeConstraint extends AbstractPropertyConstraint {
@Override
public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) {
- return getErrorMessage(toscaType, e, propertyName, "%f property value must be between >= [%s] and <= [%s]",
- String.valueOf(min), String.valueOf(max));
+ return getErrorMessage(toscaType, e, propertyName, "%f property value must be between >= [%s] and <= [%s]", String.valueOf(min),
+ String.valueOf(max));
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java
index 4b1da0ca66..3c89ed1b07 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints;
+import java.util.List;
+import java.util.Map;
+import javax.validation.constraints.NotNull;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.ToscaType;
+import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
-import java.util.List;
-import java.util.Map;
-import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException;
-
-
-import javax.validation.constraints.NotNull;
public class LengthConstraint extends AbstractPropertyConstraint {
@@ -39,9 +36,9 @@ public class LengthConstraint extends AbstractPropertyConstraint {
protected void doValidate(Object propertyValue) throws ConstraintViolationException {
if (propertyValue instanceof String && String.valueOf(propertyValue).length() != length) {
throw new ConstraintViolationException("The length of the value is not equals to [" + length + "]");
- } else if (propertyValue instanceof List && ((List) propertyValue).size() != length) {
+ } else if (propertyValue instanceof List && ((List) propertyValue).size() != length) {
throw new ConstraintViolationException("The size of the list is not equals to [" + length + "]");
- } else if (propertyValue instanceof Map && ((Map) propertyValue).size() != length) {
+ } else if (propertyValue instanceof Map && ((Map) propertyValue).size() != length) {
throw new ConstraintViolationException("The size of the map is not equals to [" + length + "]");
}
}
@@ -50,11 +47,9 @@ public class LengthConstraint extends AbstractPropertyConstraint {
if (propertyValue == null) {
throw new ConstraintViolationException("Value to validate is null");
}
-
- if(!(propertyValue instanceof String || propertyValue instanceof List || propertyValue instanceof Map)) {
+ if (!(propertyValue instanceof String || propertyValue instanceof List || propertyValue instanceof Map)) {
throw new ConstraintViolationException("This constraint can only be applied on String/List/Map value");
}
-
doValidate(propertyValue);
}
@@ -73,12 +68,10 @@ public class LengthConstraint extends AbstractPropertyConstraint {
@Override
public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException {
-
}
@Override
public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) {
return getErrorMessage(toscaType, e, propertyName, "%s length must be %s", String.valueOf(length));
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java
index c5e252b032..653c93bf29 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints;
+import javax.validation.constraints.NotNull;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException;
@@ -27,12 +27,11 @@ import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoN
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
-import javax.validation.constraints.NotNull;
-
public class LessOrEqualConstraint extends AbstractComparablePropertyConstraint {
@NotNull
private String lessOrEqual;
+
public LessOrEqualConstraint(String lessOrEqual) {
this.lessOrEqual = lessOrEqual;
}
@@ -49,7 +48,6 @@ public class LessOrEqualConstraint extends AbstractComparablePropertyConstraint
@Override
public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException {
-
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java
index a6cc5a2732..59c091f224 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java
@@ -17,9 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints;
+import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.ToscaType;
@@ -28,8 +28,6 @@ import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoN
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
-import javax.validation.constraints.NotNull;
-
@AllArgsConstructor
public class LessThanConstraint extends AbstractComparablePropertyConstraint {
@@ -48,7 +46,6 @@ public class LessThanConstraint extends AbstractComparablePropertyConstraint {
@Override
public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException {
-
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java
index e1ad08faea..2535d972ca 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java
@@ -17,21 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints;
-
-
+import java.util.List;
+import java.util.Map;
+import javax.validation.constraints.NotNull;
+import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException;
-import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
-import javax.validation.constraints.NotNull;
-import java.util.List;
-import java.util.Map;
-
public class MaxLengthConstraint extends AbstractPropertyConstraint {
@NotNull
@@ -63,7 +59,6 @@ public class MaxLengthConstraint extends AbstractPropertyConstraint {
this.maxLength = maxLength;
}
-
@Override
public ConstraintType getConstraintType() {
return null;
@@ -71,20 +66,16 @@ public class MaxLengthConstraint extends AbstractPropertyConstraint {
@Override
public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException {
-
}
-
@Override
public void validate(Object propertyValue) throws ConstraintViolationException {
if (propertyValue == null) {
throw new ConstraintViolationException("Value to validate is null");
}
-
- if(!(propertyValue instanceof String || propertyValue instanceof List || propertyValue instanceof Map)) {
+ if (!(propertyValue instanceof String || propertyValue instanceof List || propertyValue instanceof Map)) {
throw new ConstraintViolationException("This constraint can only be applied on String/List/Map value");
}
-
doValidate(propertyValue);
}
@@ -92,5 +83,4 @@ public class MaxLengthConstraint extends AbstractPropertyConstraint {
public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) {
return getErrorMessage(toscaType, e, propertyName, "%s maximum length must be [%s]", String.valueOf(maxLength));
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java
index b4a4255041..98fda80604 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints;
import java.util.List;
import java.util.Map;
-
+import javax.validation.constraints.NotNull;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
-import javax.validation.constraints.NotNull;
-
public class MinLengthConstraint extends AbstractPropertyConstraint {
@NotNull
@@ -47,9 +44,9 @@ public class MinLengthConstraint extends AbstractPropertyConstraint {
protected void doValidate(Object propertyValue) throws ConstraintViolationException {
if (propertyValue instanceof String && String.valueOf(propertyValue).length() < minLength) {
throw new ConstraintViolationException("The length of the value is less than [" + minLength + "]");
- } else if (propertyValue instanceof List && ((List) propertyValue).size() < minLength) {
+ } else if (propertyValue instanceof List && ((List) propertyValue).size() < minLength) {
throw new ConstraintViolationException("The size of the list is less than [" + minLength + "]");
- } else if (propertyValue instanceof Map && ((Map) propertyValue).size() < minLength) {
+ } else if (propertyValue instanceof Map && ((Map) propertyValue).size() < minLength) {
throw new ConstraintViolationException("The size of the map is less than [" + minLength + "]");
}
}
@@ -69,7 +66,6 @@ public class MinLengthConstraint extends AbstractPropertyConstraint {
@Override
public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException {
-
}
@Override
@@ -77,7 +73,7 @@ public class MinLengthConstraint extends AbstractPropertyConstraint {
if (propertyValue == null) {
throw new ConstraintViolationException("Value to validate is null");
}
- if(!(propertyValue instanceof String || propertyValue instanceof List || propertyValue instanceof Map)) {
+ if (!(propertyValue instanceof String || propertyValue instanceof List || propertyValue instanceof Map)) {
throw new ConstraintViolationException("This constraint can only be applied on String/List/Map value");
}
doValidate(propertyValue);
@@ -87,5 +83,4 @@ public class MinLengthConstraint extends AbstractPropertyConstraint {
public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) {
return getErrorMessage(toscaType, e, propertyName, "%s minimum length must be [%s]", String.valueOf(minLength));
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java
index 49e40cf9c2..e3f4d3e7e3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints;
import java.util.regex.Pattern;
-
+import javax.validation.constraints.NotNull;
+import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException;
-import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
-import javax.validation.constraints.NotNull;
-
public class PatternConstraint extends AbstractStringPropertyConstraint {
@NotNull
private String pattern;
-
private Pattern compiledPattern;
public void setPattern(String pattern) {
@@ -56,14 +52,10 @@ public class PatternConstraint extends AbstractStringPropertyConstraint {
@Override
public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException {
-
}
@Override
public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) {
- return getErrorMessage(toscaType, e, propertyName, "%s property value must match the regular expression %s",
- pattern);
+ return getErrorMessage(toscaType, e, propertyName, "%s property value must match the regular expression %s", pattern);
}
-
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java
index 2ab0673cfe..fb4685d716 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints;
+import static java.util.stream.Collectors.toList;
+
import com.google.common.collect.Sets;
+import java.util.List;
+import java.util.Set;
+import javax.validation.constraints.NotNull;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.ToscaType;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException;
import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
-import javax.validation.constraints.NotNull;
-import java.util.List;
-import java.util.Set;
-import static java.util.stream.Collectors.toList;
-
-
public class ValidValuesConstraint extends AbstractPropertyConstraint {
+ private static final String PROPERTY_TYPE_IS = "> property type is <";
@NotNull
private List<String> validValues;
private Set<Object> validValuesTyped;
- private static final String PROPERTY_TYPE_IS = "> property type is <";
public ValidValuesConstraint(List<String> validValues) {
this.validValues = validValues;
@@ -54,12 +52,12 @@ public class ValidValuesConstraint extends AbstractPropertyConstraint {
validValuesTyped = Sets.newHashSet();
if (validValues == null) {
throw new ConstraintValueDoNotMatchPropertyTypeException(
- "validValues constraint has invalid value <> property type is <" + propertyType.toString() + ">");
+ "validValues constraint has invalid value <> property type is <" + propertyType.toString() + ">");
}
for (String value : validValues) {
if (!propertyType.isValidValue(value)) {
- throw new ConstraintValueDoNotMatchPropertyTypeException("validValues constraint has invalid value <"
- + value + PROPERTY_TYPE_IS + propertyType.toString() + ">");
+ throw new ConstraintValueDoNotMatchPropertyTypeException(
+ "validValues constraint has invalid value <" + value + PROPERTY_TYPE_IS + propertyType.toString() + ">");
} else {
validValuesTyped.add(propertyType.convert(value));
}
@@ -67,31 +65,31 @@ public class ValidValuesConstraint extends AbstractPropertyConstraint {
}
public void validateType(String propertyType) throws ConstraintValueDoNotMatchPropertyTypeException {
- ToscaType toscaType= ToscaType.getToscaType(propertyType);
- if(toscaType == null){
- throw new ConstraintValueDoNotMatchPropertyTypeException("validValues constraint has invalid values <"
- + validValues.toString() + PROPERTY_TYPE_IS + propertyType + ">");
+ ToscaType toscaType = ToscaType.getToscaType(propertyType);
+ if (toscaType == null) {
+ throw new ConstraintValueDoNotMatchPropertyTypeException(
+ "validValues constraint has invalid values <" + validValues.toString() + PROPERTY_TYPE_IS + propertyType + ">");
}
if (validValues == null) {
throw new ConstraintValueDoNotMatchPropertyTypeException(
- "validValues constraint has invalid value <> property type is <" + propertyType + ">");
+ "validValues constraint has invalid value <> property type is <" + propertyType + ">");
}
for (String value : validValues) {
if (!toscaType.isValidValue(value)) {
- throw new ConstraintValueDoNotMatchPropertyTypeException("validValues constraint has invalid value <"
- + value + PROPERTY_TYPE_IS + propertyType + ">");
+ throw new ConstraintValueDoNotMatchPropertyTypeException(
+ "validValues constraint has invalid value <" + value + PROPERTY_TYPE_IS + propertyType + ">");
}
}
}
@Override
public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException {
- if(newConstraint.getConstraintType() == getConstraintType()){
- if(!((ValidValuesConstraint)newConstraint).getValidValues().containsAll(validValues)){
- throw new PropertyConstraintException("Deletion of exists value is not permitted", null, null, ActionStatus.CANNOT_DELETE_VALID_VALUES, getConstraintType().name(),
- validValues.stream()
- .filter(v->!((ValidValuesConstraint)newConstraint).getValidValues().contains(v))
- .collect(toList()).toString());
+ if (newConstraint.getConstraintType() == getConstraintType()) {
+ if (!((ValidValuesConstraint) newConstraint).getValidValues().containsAll(validValues)) {
+ throw new PropertyConstraintException("Deletion of exists value is not permitted", null, null,
+ ActionStatus.CANNOT_DELETE_VALID_VALUES, getConstraintType().name(),
+ validValues.stream().filter(v -> !((ValidValuesConstraint) newConstraint).getValidValues().contains(v)).collect(toList())
+ .toString());
}
}
}
@@ -121,8 +119,6 @@ public class ValidValuesConstraint extends AbstractPropertyConstraint {
@Override
public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) {
- return getErrorMessage(toscaType, e, propertyName, "%s valid value must be one of the following: [%s]",
- String.join(",", validValues));
+ return getErrorMessage(toscaType, e, propertyName, "%s valid value must be one of the following: [%s]", String.join(",", validValues));
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintFunctionalException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintFunctionalException.java
index a29bb01074..9535892550 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintFunctionalException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintFunctionalException.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints.exception;
import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInformation;
/**
* All functional error related to constraint processing must go here
- *
+ *
* @author mkv
- *
*/
public class ConstraintFunctionalException extends FunctionalException {
@@ -44,5 +42,4 @@ public class ConstraintFunctionalException extends FunctionalException {
super(message, cause);
this.constraintInformation = constraintInformation;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintRequiredParameterException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintRequiredParameterException.java
index 5c97a477c6..035e5407e6 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintRequiredParameterException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintRequiredParameterException.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints.exception;
import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInformation;
/**
* Exception to be thrown when a required property is not provided
- *
- * @author mourouvi
*
+ * @author mourouvi
*/
public class ConstraintRequiredParameterException extends ConstraintFunctionalException {
@@ -41,5 +39,4 @@ public class ConstraintRequiredParameterException extends ConstraintFunctionalEx
public ConstraintRequiredParameterException(String message, Throwable cause, ConstraintInformation constraintInformation) {
super(message, cause, constraintInformation);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintTechnicalException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintTechnicalException.java
index f669e8429b..d565580c16 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintTechnicalException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintTechnicalException.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints.exception;
/**
* Base class for all constraint related exceptions
- *
+ *
* @author esofer
- *
*/
public class ConstraintTechnicalException extends Exception {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintValueDoNotMatchPropertyTypeException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintValueDoNotMatchPropertyTypeException.java
index 4adefb96de..60548a612f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintValueDoNotMatchPropertyTypeException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintValueDoNotMatchPropertyTypeException.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints.exception;
import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInformation;
/**
- * Exception to be thrown when a constraint definition is invalid because the
- * specified value doesn't match the property type.
- *
+ * Exception to be thrown when a constraint definition is invalid because the specified value doesn't match the property type.
+ *
* @author esofer
*/
public class ConstraintValueDoNotMatchPropertyTypeException extends ConstraintFunctionalException {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintViolationException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintViolationException.java
index 3101b7b521..1938063085 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintViolationException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/ConstraintViolationException.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.constraints.exception;
import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil.ConstraintInformation;
/**
* Exception happened while user violated a predefined constraint
- *
+ *
* @author mkv
- *
*/
public class ConstraintViolationException extends ConstraintFunctionalException {
@@ -41,5 +39,4 @@ public class ConstraintViolationException extends ConstraintFunctionalException
public ConstraintViolationException(String message, Throwable cause, ConstraintInformation constraintInformation) {
super(message, cause, constraintInformation);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/FunctionalException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/FunctionalException.java
index 4ffc5f030b..62e90c1e36 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/FunctionalException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/FunctionalException.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints.exception;
/**
- * All functional exception which is related to user input must go here. It's a
- * checked exception to force error handling and checking.
- *
+ * All functional exception which is related to user input must go here. It's a checked exception to force error handling and checking.
+ *
* @author mkv
- *
*/
public class FunctionalException extends Exception {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/InvalidPropertyConstraintImplementationException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/InvalidPropertyConstraintImplementationException.java
index f4d920bea2..138a24bc8a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/InvalidPropertyConstraintImplementationException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/InvalidPropertyConstraintImplementationException.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints.exception;
/**
* Exception thrown when the user defines invalid custom property constraint
- *
+ *
* @author mkv
- *
*/
public class InvalidPropertyConstraintImplementationException extends ConstraintTechnicalException {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/PropertyConstraintException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/PropertyConstraintException.java
index 3fbf4dd3d4..3375587837 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/PropertyConstraintException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/PropertyConstraintException.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints.exception;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -28,7 +27,8 @@ public class PropertyConstraintException extends ConstraintFunctionalException {
private final ActionStatus actionStatus;
private final String[] params;
- public PropertyConstraintException(String message, Throwable cause, ConstraintUtil.ConstraintInformation constraintInformation, ActionStatus actionStatus, String... params) {
+ public PropertyConstraintException(String message, Throwable cause, ConstraintUtil.ConstraintInformation constraintInformation,
+ ActionStatus actionStatus, String... params) {
super(message, cause, constraintInformation);
this.actionStatus = actionStatus;
this.params = params;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/TechnicalException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/TechnicalException.java
index 5d369a08a4..296db3e760 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/TechnicalException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/TechnicalException.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.constraints.exception;
/**
* Base class for all Alien technical exception
*
* @author mkv
- *
*/
public abstract class TechnicalException extends RuntimeException {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverter.java
index 9ff43926a4..3109f54f4a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/BooleanConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class BooleanConverter implements ToscaValueConverter {
- private static BooleanConverter booleanConverter = new BooleanConverter();
- public static BooleanConverter getInstance() {
- return booleanConverter;
- }
+ private static BooleanConverter booleanConverter = new BooleanConverter();
private BooleanConverter() {
+ }
+ public static BooleanConverter getInstance() {
+ return booleanConverter;
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java
index e4d7fc7ec4..2c1f862ece 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.converters;
import com.google.gson.Gson;
@@ -47,9 +46,8 @@ public class DataTypePropertyConverter {
}
/**
- *
* @param propertyDataType the data type
- * @param dataTypes all data types in the system mapped by their name
+ * @param dataTypes all data types in the system mapped by their name
* @return a json representation of all the given data type properties default values and recursively their data type properties
*/
public String getDataTypePropertiesDefaultValuesRec(String propertyDataType, Map<String, DataTypeDefinition> dataTypes) {
@@ -59,11 +57,11 @@ public class DataTypePropertyConverter {
/**
* Takes a json representation of a tosca property value and merges all the default values of the property data type
- * @param value the json representation of a tosca property value
+ *
+ * @param value the json representation of a tosca property value
* @param propertyDataType data type from which to merge default values
- * @param dataTypes all data types in the system mapped by their name
- * for example: for value {a: {b: c}} we could have a default value {a: {d: e}} (property a has two sub properties but only b was overridden)
- * so the complete value is {a: {b: c, d: e}}
+ * @param dataTypes all data types in the system mapped by their name for example: for value {a: {b: c}} we could have a default value {a:
+ * {d: e}} (property a has two sub properties but only b was overridden) so the complete value is {a: {b: c, d: e}}
*/
public void mergeDataTypeDefaultValuesWithPropertyValue(JsonObject value, String propertyDataType, Map<String, DataTypeDefinition> dataTypes) {
JsonObject dataTypeDefaultValues = getDataTypePropsDefaultValuesRec(propertyDataType, dataTypes);
@@ -106,7 +104,8 @@ public class DataTypePropertyConverter {
return dataTypeDefaultsJson;
}
- private void addDefaultValueToJson(Map<String, DataTypeDefinition> dataTypes, JsonObject dataTypePropsDefaults, PropertyDefinition propertyDefinition) {
+ private void addDefaultValueToJson(Map<String, DataTypeDefinition> dataTypes, JsonObject dataTypePropsDefaults,
+ PropertyDefinition propertyDefinition) {
String propName = propertyDefinition.getName();
JsonElement defVal = getDefaultValue(dataTypes, dataTypePropsDefaults, propertyDefinition);
if (!JsonUtils.isEmptyJson(defVal)) {
@@ -114,11 +113,12 @@ public class DataTypePropertyConverter {
}
}
- private JsonElement getDefaultValue(Map<String, DataTypeDefinition> dataTypes, JsonObject dataTypePropsDefaults, PropertyDefinition propertyDefinition) {
+ private JsonElement getDefaultValue(Map<String, DataTypeDefinition> dataTypes, JsonObject dataTypePropsDefaults,
+ PropertyDefinition propertyDefinition) {
JsonElement defVal = new JsonObject();
String propName = propertyDefinition.getName();
String propDefaultVal = propertyDefinition.getDefaultValue();
- if(!JsonUtils.containsEntry(dataTypePropsDefaults, propName) && propDefaultVal != null){
+ if (!JsonUtils.containsEntry(dataTypePropsDefaults, propName) && propDefaultVal != null) {
defVal = convertToJson(propDefaultVal);
} else if (!JsonUtils.containsEntry(dataTypePropsDefaults, propName)) {
defVal = getDataTypePropsDefaultValuesRec(propertyDefinition.getType(), dataTypes);
@@ -135,15 +135,12 @@ public class DataTypePropertyConverter {
private Map<String, PropertyDefinition> getAllDataTypeProperties(DataTypeDefinition dataTypeDefinition) {
Map<String, PropertyDefinition> allParentsProps = new HashMap<>();
while (dataTypeDefinition != null) {
-
List<PropertyDefinition> currentParentsProps = dataTypeDefinition.getProperties();
if (currentParentsProps != null) {
currentParentsProps.stream().forEach(p -> allParentsProps.put(p.getName(), p));
}
-
dataTypeDefinition = dataTypeDefinition.getDerivedFrom();
}
return allParentsProps;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverter.java
index 11c0340a91..990c51b616 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DefaultConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class DefaultConverter implements PropertyValueConverter {
private static DefaultConverter defaultConverter = new DefaultConverter();
- public static DefaultConverter getInstance() {
- return defaultConverter;
- }
-
private DefaultConverter() {
+ }
+ public static DefaultConverter getInstance() {
+ return defaultConverter;
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverter.java
index 2d2ac72ca5..65ff297bb2 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/FloatConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class FloatConverter implements ToscaValueConverter {
- private static FloatConverter floatConverter = new FloatConverter();
- public static FloatConverter getInstance() {
- return floatConverter;
- }
+ private static FloatConverter floatConverter = new FloatConverter();
private FloatConverter() {
+ }
+ public static FloatConverter getInstance() {
+ return floatConverter;
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java
index 77f49319bd..d4208dd01c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,38 +17,32 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class HeatBooleanConverter implements PropertyValueConverter {
private static HeatBooleanConverter booleanConverter = new HeatBooleanConverter();
- public static HeatBooleanConverter getInstance() {
- return booleanConverter;
- }
-
private HeatBooleanConverter() {
+ }
+ public static HeatBooleanConverter getInstance() {
+ return booleanConverter;
}
@Override
public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
-
if (value == null || value.isEmpty()) {
return null;
}
-
- if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("t") || value.equalsIgnoreCase("on")
- || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("y") || value.equalsIgnoreCase("1")) {
+ if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("t") || value.equalsIgnoreCase("on") || value.equalsIgnoreCase("yes") || value
+ .equalsIgnoreCase("y") || value.equalsIgnoreCase("1")) {
return "true";
} else {
return "false";
}
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java
index 04c2a7dd1f..86aa3137a7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.converters;
+import java.util.Map;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.common.util.ValidationUtils;
-import java.util.Map;
-
public class HeatCommaDelimitedListConverter implements PropertyValueConverter {
private static HeatCommaDelimitedListConverter stringConverter = new HeatCommaDelimitedListConverter();
- public static HeatCommaDelimitedListConverter getInstance() {
- return stringConverter;
- }
-
private HeatCommaDelimitedListConverter() {
+ }
+ public static HeatCommaDelimitedListConverter getInstance() {
+ return stringConverter;
}
@Override
public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) {
String coverted = null;
- if(original != null){
+ if (original != null) {
coverted = ValidationUtils.removeNoneUtf8Chars(original);
coverted = ValidationUtils.removeHtmlTagsOnly(coverted);
coverted = ValidationUtils.normaliseWhitespace(coverted);
@@ -48,5 +45,4 @@ public class HeatCommaDelimitedListConverter implements PropertyValueConverter {
}
return coverted;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java
index 90618ced45..db3b786d37 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.converters;
+import java.util.Map;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.common.util.ValidationUtils;
-import java.util.Map;
-
public class HeatJsonConverter implements PropertyValueConverter {
private static HeatJsonConverter jsonConverter = new HeatJsonConverter();
- public static HeatJsonConverter getInstance() {
- return jsonConverter;
- }
-
private HeatJsonConverter() {
+ }
+ public static HeatJsonConverter getInstance() {
+ return jsonConverter;
}
@Override
@@ -49,5 +46,4 @@ public class HeatJsonConverter implements PropertyValueConverter {
// As opposed to string converter, keeping the " and ' symbols
return converted;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java
index 187793ee0b..98567bb009 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.math.BigDecimal;
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class HeatNumberConverter implements PropertyValueConverter {
private static HeatNumberConverter numberConverter = new HeatNumberConverter();
- public static HeatNumberConverter getInstance() {
- return numberConverter;
- }
-
private HeatNumberConverter() {
+ }
+ public static HeatNumberConverter getInstance() {
+ return numberConverter;
}
@Override
public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) {
-
if (original == null || original.isEmpty()) {
return null;
}
-
return new BigDecimal(original).toPlainString();
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java
index 3bc379c7f9..e6c0089d6c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.converters;
+import java.util.Map;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.common.util.ValidationUtils;
-import java.util.Map;
-
public class HeatStringConverter implements PropertyValueConverter {
private static HeatStringConverter stringConverter = new HeatStringConverter();
- public static HeatStringConverter getInstance() {
- return stringConverter;
- }
-
private HeatStringConverter() {
+ }
+ public static HeatStringConverter getInstance() {
+ return stringConverter;
}
@Override
public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) {
String coverted = null;
- if(original != null){
+ if (original != null) {
coverted = ValidationUtils.removeNoneUtf8Chars(original);
coverted = ValidationUtils.normaliseWhitespace(coverted);
coverted = ValidationUtils.stripOctets(coverted);
@@ -48,5 +45,4 @@ public class HeatStringConverter implements PropertyValueConverter {
}
return coverted;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java
index f5e0a61358..205c977001 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,27 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class IntegerConverter implements ToscaValueConverter {
private static IntegerConverter integerConverter = new IntegerConverter();
- public static IntegerConverter getInstance() {
- return integerConverter;
- }
-
private IntegerConverter() {
+ }
+ public static IntegerConverter getInstance() {
+ return integerConverter;
}
@Override
public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- if ( value == null || value.isEmpty() ){
+ if (value == null || value.isEmpty()) {
return null;
}
return Integer.parseInt(value);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverter.java
index db2004aab4..d773f03e56 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/JsonConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.common.util.GsonFactory;
-
import java.io.StringReader;
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.common.util.GsonFactory;
public class JsonConverter implements PropertyValueConverter {
private static JsonConverter jsonConverter = new JsonConverter();
-
private static JsonParser jsonParser = new JsonParser();
-
private static Gson gson = GsonFactory.getGson();
- public static JsonConverter getInstance() {
- return jsonConverter;
- }
-
private JsonConverter() {
+ }
+ public static JsonConverter getInstance() {
+ return jsonConverter;
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java
index 00783404e7..3ae725eb7c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import com.google.gson.*;
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonParser;
import fj.data.Either;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.model.DataTypeDefinition;
@@ -32,20 +39,13 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.GsonFactory;
import org.openecomp.sdc.common.util.JsonUtils;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
public class ListConverter implements PropertyValueConverter {
+ private static final Logger log = Logger.getLogger(ListValidator.class.getName());
private static ListConverter listConverter = new ListConverter();
private static Gson gson = GsonFactory.getGson();
- private static final Logger log = Logger.getLogger(ListValidator.class.getName());
-
- DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
-
private static JsonParser jsonParser = new JsonParser();
+ DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
public static ListConverter getInstance() {
return listConverter;
@@ -57,142 +57,123 @@ public class ListConverter implements PropertyValueConverter {
if (convertWithErrorResult.isRight()) {
return null;
}
-
return convertWithErrorResult.left().value();
}
- public Either<String, Boolean> convertWithErrorResult(String value, String innerType,
- Map<String, DataTypeDefinition> dataTypes) {
+ public Either<String, Boolean> convertWithErrorResult(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
if (value == null || innerType == null) {
return Either.left(value);
}
-
PropertyValueConverter innerConverter;
ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
-
if (innerToscaType != null) {
PropertyValueConverter innerConverter1;
switch (innerToscaType) {
- case STRING:
- innerConverter1 = ToscaPropertyType.STRING.getConverter();
- break;
- case INTEGER:
- innerConverter1 = ToscaPropertyType.INTEGER.getConverter();
- break;
- case FLOAT:
- innerConverter1 = ToscaPropertyType.FLOAT.getConverter();
- break;
- case BOOLEAN:
- innerConverter1 = ToscaPropertyType.BOOLEAN.getConverter();
- break;
- case JSON:
- innerConverter1 = ToscaPropertyType.JSON.getConverter();
- break;
- default:
- log.debug("inner Tosca Type is unknown");
- return Either.left(value);
+ case STRING:
+ innerConverter1 = ToscaPropertyType.STRING.getConverter();
+ break;
+ case INTEGER:
+ innerConverter1 = ToscaPropertyType.INTEGER.getConverter();
+ break;
+ case FLOAT:
+ innerConverter1 = ToscaPropertyType.FLOAT.getConverter();
+ break;
+ case BOOLEAN:
+ innerConverter1 = ToscaPropertyType.BOOLEAN.getConverter();
+ break;
+ case JSON:
+ innerConverter1 = ToscaPropertyType.JSON.getConverter();
+ break;
+ default:
+ log.debug("inner Tosca Type is unknown");
+ return Either.left(value);
}
innerConverter = innerConverter1;
} else {
log.debug("inner Tosca Type {} ia a complex data type.", innerType);
-
return convertComplexInnerType(value, innerType, dataTypes);
}
-
try {
ArrayList<String> newList = new ArrayList<>();
-
JsonArray jo = (JsonArray) jsonParser.parse(value);
- if(ToscaPropertyType.JSON == innerToscaType)
+ if (ToscaPropertyType.JSON == innerToscaType) {
return Either.left(value);
+ }
int size = jo.size();
for (int i = 0; i < size; i++) {
JsonElement currentValue = jo.get(i);
String element = JsonUtils.toString(currentValue);
-
if (element == null || element.isEmpty()) {
continue;
}
element = innerConverter.convert(element, null, dataTypes);
newList.add(element);
}
-
switch (innerToscaType) {
- case STRING:
- value = gson.toJson(newList);
- break;
- case INTEGER:
- List<BigInteger> intList = new ArrayList<>();
-
- for (String str : newList) {
- int base = 10;
- if (str.contains("0x")) {
- str = str.replaceFirst("0x", "");
- base = 16;
+ case STRING:
+ value = gson.toJson(newList);
+ break;
+ case INTEGER:
+ List<BigInteger> intList = new ArrayList<>();
+ for (String str : newList) {
+ int base = 10;
+ if (str.contains("0x")) {
+ str = str.replaceFirst("0x", "");
+ base = 16;
+ }
+ if (str.contains("0o")) {
+ str = str.replaceFirst("0o", "");
+ base = 8;
+ }
+ intList.add(new BigInteger(str, base));
}
- if (str.contains("0o")) {
- str = str.replaceFirst("0o", "");
- base = 8;
+ value = gson.toJson(intList);
+ break;
+ case FLOAT:
+ value = "[";
+ for (String str : newList) {
+ value += str + ",";
}
- intList.add(new BigInteger(str, base));
- }
- value = gson.toJson(intList);
- break;
- case FLOAT:
- value = "[";
- for (String str : newList) {
- value += str + ",";
- }
- value = value.substring(0, value.length() - 1);
- value += "]";
- break;
- case BOOLEAN:
- List<Boolean> boolList = new ArrayList<>();
- for (String str : newList) {
- boolList.add(Boolean.valueOf(str));
- }
- value = gson.toJson(boolList);
- break;
- default:
- value = gson.toJson(newList);
- log.debug("inner Tosca Type unknown : {}", innerToscaType);
+ value = value.substring(0, value.length() - 1);
+ value += "]";
+ break;
+ case BOOLEAN:
+ List<Boolean> boolList = new ArrayList<>();
+ for (String str : newList) {
+ boolList.add(Boolean.valueOf(str));
+ }
+ value = gson.toJson(boolList);
+ break;
+ default:
+ value = gson.toJson(newList);
+ log.debug("inner Tosca Type unknown : {}", innerToscaType);
}
-
} catch (JsonParseException e) {
log.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter");
return Either.right(false);
}
-
return Either.left(value);
}
- private Either<String, Boolean> convertComplexInnerType(String value, String innerType,
- Map<String, DataTypeDefinition> allDataTypes) {
-
+ private Either<String, Boolean> convertComplexInnerType(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
DataTypeDefinition dataTypeDefinition = allDataTypes.get(innerType);
if (dataTypeDefinition == null) {
log.debug("Cannot find data type {}", innerType);
return Either.right(false);
}
-
List<JsonElement> newList = new ArrayList<>();
-
try {
-
JsonArray jo = (JsonArray) jsonParser.parse(value);
int size = jo.size();
for (int i = 0; i < size; i++) {
JsonElement currentValue = jo.get(i);
-
if (currentValue != null) {
-
String element = JsonUtils.toString(currentValue);
-
ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter
- .validateAndUpdate(element, dataTypeDefinition, allDataTypes);
+ .validateAndUpdate(element, dataTypeDefinition, allDataTypes);
if (!validateAndUpdate.right.booleanValue()) {
- log.debug("Cannot parse value {} from type {} in list position {}",currentValue,innerType,i);
+ log.debug("Cannot parse value {} from type {} in list position {}", currentValue, innerType, i);
return Either.right(false);
}
JsonElement newValue = validateAndUpdate.left;
@@ -206,5 +187,4 @@ public class ListConverter implements PropertyValueConverter {
value = gson.toJson(newList);
return Either.left(value);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverter.java
index 6e799dac83..16823ad31c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/LowerCaseConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,32 +17,27 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class LowerCaseConverter implements PropertyValueConverter {
private static LowerCaseConverter booleanConverter = new LowerCaseConverter();
- public static LowerCaseConverter getInstance() {
- return booleanConverter;
- }
-
private LowerCaseConverter() {
+ }
+ public static LowerCaseConverter getInstance() {
+ return booleanConverter;
}
@Override
public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
-
if (value == null) {
return null;
}
return value.toLowerCase();
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java
index 3be610ec53..23dc10ea0e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
import com.google.common.base.Strings;
-import com.google.gson.*;
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonParser;
import fj.data.Either;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.model.DataTypeDefinition;
@@ -33,153 +40,126 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.GsonFactory;
import org.openecomp.sdc.common.util.JsonUtils;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
public class MapConverter implements PropertyValueConverter {
+ private static final Logger log = Logger.getLogger(ListValidator.class.getName());
private static MapConverter mapConverter = new MapConverter();
private static Gson gson = GsonFactory.getGson();
- private static final Logger log = Logger.getLogger(ListValidator.class.getName());
-
- DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
-
private static JsonParser jsonParser = new JsonParser();
+ DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
public static MapConverter getInstance() {
return mapConverter;
}
public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
-
Either<String, Boolean> convertWithErrorResult = this.convertWithErrorResult(value, innerType, dataTypes);
if (convertWithErrorResult.isRight()) {
return null;
}
-
return convertWithErrorResult.left().value();
}
- public Either<String, Boolean> convertWithErrorResult(String value, String innerType,
- Map<String, DataTypeDefinition> dataTypes) {
-
+ public Either<String, Boolean> convertWithErrorResult(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
if (Strings.isNullOrEmpty(value) || innerType == null) {
return Either.left(value);
}
-
PropertyValueConverter innerConverter;
PropertyValueConverter keyConverter = ToscaPropertyType.STRING.getConverter();
ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
-
if (innerToscaType != null) {
switch (innerToscaType) {
- case STRING:
- innerConverter = ToscaPropertyType.STRING.getConverter();
- break;
- case INTEGER:
- innerConverter = ToscaPropertyType.INTEGER.getConverter();
- break;
- case FLOAT:
- innerConverter = ToscaPropertyType.FLOAT.getConverter();
- break;
- case BOOLEAN:
- innerConverter = ToscaPropertyType.BOOLEAN.getConverter();
- break;
- case JSON:
- innerConverter = ToscaPropertyType.JSON.getConverter();
- break;
- default:
- log.debug("inner Tosca Type is unknown");
- return Either.left(value);
+ case STRING:
+ innerConverter = ToscaPropertyType.STRING.getConverter();
+ break;
+ case INTEGER:
+ innerConverter = ToscaPropertyType.INTEGER.getConverter();
+ break;
+ case FLOAT:
+ innerConverter = ToscaPropertyType.FLOAT.getConverter();
+ break;
+ case BOOLEAN:
+ innerConverter = ToscaPropertyType.BOOLEAN.getConverter();
+ break;
+ case JSON:
+ innerConverter = ToscaPropertyType.JSON.getConverter();
+ break;
+ default:
+ log.debug("inner Tosca Type is unknown");
+ return Either.left(value);
}
-
} else {
-
log.debug("inner Tosca Type {} ia a complex data type.", innerType);
-
- return convertComplexInnerType(value, innerType, keyConverter,
- dataTypes);
-
+ return convertComplexInnerType(value, innerType, keyConverter, dataTypes);
}
-
try {
Map<String, String> newMap = new HashMap<>();
-
JsonElement jsonObject = jsonParser.parse(value);
JsonObject asJsonObject = jsonObject.getAsJsonObject();
Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
for (Entry<String, JsonElement> entry : entrySet) {
String key = entry.getKey();
JsonElement jsonValue = entry.getValue();
-
key = keyConverter.convert(entry.getKey(), null, dataTypes);
-
String element = JsonUtils.toString(jsonValue);
-
String val = innerConverter.convert(element, null, dataTypes);
newMap.put(key, val);
}
-
String objVal;
switch (innerToscaType) {
- case STRING:
- value = gson.toJson(newMap);
- break;
- case INTEGER:
- String key = null;
- Map<String, Integer> intMap = new HashMap<>();
- for (Map.Entry<String, String> entry : newMap.entrySet()) {
- objVal = entry.getValue();
- key = entry.getKey();
- if (objVal != null) {
- intMap.put(key, Integer.valueOf(objVal.toString()));
- } else {
- intMap.put(key, null);
+ case STRING:
+ value = gson.toJson(newMap);
+ break;
+ case INTEGER:
+ String key = null;
+ Map<String, Integer> intMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : newMap.entrySet()) {
+ objVal = entry.getValue();
+ key = entry.getKey();
+ if (objVal != null) {
+ intMap.put(key, Integer.valueOf(objVal.toString()));
+ } else {
+ intMap.put(key, null);
+ }
}
-
- }
- value = gson.toJson(intMap);
- break;
- case FLOAT:
- value = "{";
- for (Map.Entry<String, String> entry : newMap.entrySet()) {
- objVal = entry.getValue();
- if (objVal == null) {
- objVal = "null";
+ value = gson.toJson(intMap);
+ break;
+ case FLOAT:
+ value = "{";
+ for (Map.Entry<String, String> entry : newMap.entrySet()) {
+ objVal = entry.getValue();
+ if (objVal == null) {
+ objVal = "null";
+ }
+ key = entry.getKey();
+ value += "\"" + key + "\":" + objVal.toString() + ",";
}
- key = entry.getKey();
- value += "\"" + key + "\":" + objVal.toString() + ",";
- }
- value = value.substring(0, value.length() - 1);
- value += "}";
- break;
- case BOOLEAN:
- Map<String, Boolean> boolMap = new HashMap<>();
- for (Map.Entry<String, String> entry : newMap.entrySet()) {
- objVal = entry.getValue();
- key = entry.getKey();
- if (objVal != null) {
- boolMap.put(key, Boolean.valueOf(objVal.toString()));
- } else {
- boolMap.put(key, null);
+ value = value.substring(0, value.length() - 1);
+ value += "}";
+ break;
+ case BOOLEAN:
+ Map<String, Boolean> boolMap = new HashMap<>();
+ for (Map.Entry<String, String> entry : newMap.entrySet()) {
+ objVal = entry.getValue();
+ key = entry.getKey();
+ if (objVal != null) {
+ boolMap.put(key, Boolean.valueOf(objVal.toString()));
+ } else {
+ boolMap.put(key, null);
+ }
}
- }
- value = gson.toJson(boolMap);
- break;
- default:
- value = gson.toJson(newMap);
- log.debug("inner Tosca Type unknown : {}", innerToscaType);
+ value = gson.toJson(boolMap);
+ break;
+ default:
+ value = gson.toJson(newMap);
+ log.debug("inner Tosca Type unknown : {}", innerToscaType);
}
} catch (JsonParseException e) {
log.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Converter");
return Either.right(false);
}
-
return Either.left(value);
-
}
/**
@@ -191,35 +171,27 @@ public class MapConverter implements PropertyValueConverter {
* @param allDataTypes
* @return
*/
- private Either<String, Boolean> convertComplexInnerType(String value, String innerType,
- PropertyValueConverter keyConverter, Map<String, DataTypeDefinition> allDataTypes) {
-
+ private Either<String, Boolean> convertComplexInnerType(String value, String innerType, PropertyValueConverter keyConverter,
+ Map<String, DataTypeDefinition> allDataTypes) {
DataTypeDefinition dataTypeDefinition = allDataTypes.get(innerType);
if (dataTypeDefinition == null) {
log.debug("Cannot find data type {}", innerType);
return Either.right(false);
}
-
Map<String, JsonElement> newMap = new HashMap<>();
-
try {
-
JsonElement jsonObject = jsonParser.parse(value);
JsonObject asJsonObject = jsonObject.getAsJsonObject();
Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
for (Entry<String, JsonElement> entry : entrySet) {
String currentKey = keyConverter.convert(entry.getKey(), null, allDataTypes);
-
JsonElement currentValue = entry.getValue();
-
if (currentValue != null) {
-
String element = JsonUtils.toString(currentValue);
-
ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter
- .validateAndUpdate(element, dataTypeDefinition, allDataTypes);
+ .validateAndUpdate(element, dataTypeDefinition, allDataTypes);
if (!validateAndUpdate.right.booleanValue()) {
- log.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey);
+ log.debug("Cannot parse value {} from type {} of key {}", currentValue, innerType, currentKey);
return Either.right(false);
}
JsonElement newValue = validateAndUpdate.left;
@@ -228,14 +200,11 @@ public class MapConverter implements PropertyValueConverter {
newMap.put(currentKey, null);
}
}
-
} catch (Exception e) {
log.debug("Cannot parse value {} of map from inner type {}", value, innerType);
return Either.right(false);
}
-
value = gson.toJson(newMap);
return Either.left(value);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/PropertyValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/PropertyValueConverter.java
index b60b0a5ec8..705705fc2f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/PropertyValueConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/PropertyValueConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public interface PropertyValueConverter {
String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes);
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertor.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertor.java
index ae5340720c..c12d93539e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertor.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/StringConvertor.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.converters;
+import java.util.Map;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.common.util.ValidationUtils;
-import java.util.Map;
-
public class StringConvertor implements PropertyValueConverter {
private static StringConvertor stringConverter = new StringConvertor();
- public static StringConvertor getInstance() {
- return stringConverter;
- }
-
private StringConvertor() {
+ }
+ public static StringConvertor getInstance() {
+ return stringConverter;
}
@Override
@@ -43,13 +40,10 @@ public class StringConvertor implements PropertyValueConverter {
return null;
}
String coverted = ValidationUtils.removeNoneUtf8Chars(original);
-
// coverted = ValidationUtils.convertHtmlTagsToEntities(coverted);
coverted = ValidationUtils.normaliseWhitespace(coverted);
coverted = ValidationUtils.stripOctets(coverted);
coverted = ValidationUtils.removeHtmlTagsOnly(coverted);
-
return coverted;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverter.java
index 346f637306..e36b7d9768 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaBooleanConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,38 +17,31 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class ToscaBooleanConverter implements PropertyValueConverter {
private static ToscaBooleanConverter booleanConverter = new ToscaBooleanConverter();
- public static ToscaBooleanConverter getInstance() {
- return booleanConverter;
- }
-
private ToscaBooleanConverter() {
+ }
+ public static ToscaBooleanConverter getInstance() {
+ return booleanConverter;
}
@Override
public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
-
if (value == null) {
return null;
}
-
- if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on") || value.equalsIgnoreCase("yes")
- || value.equalsIgnoreCase("y")) {
+ if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("y")) {
return "true";
} else {
return "false";
}
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java
index 7ce9103f8a..d40f84fe74 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.converters;
import com.google.gson.JsonObject;
@@ -25,7 +24,8 @@ import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
public class ToscaConverterUtils {
- private ToscaConverterUtils() {}
+ private ToscaConverterUtils() {
+ }
public static boolean isGetInputValue(JsonObject value) {
return value.get(ToscaFunctions.GET_INPUT.getFunctionName()) != null;
@@ -34,5 +34,4 @@ public class ToscaConverterUtils {
public static boolean isGetPolicyValue(JsonObject value) {
return value.get(ToscaFunctions.GET_POLICY.getFunctionName()) != null;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java
index 417beea5fe..e906f58828 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java
@@ -17,20 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.apache.commons.lang.StringUtils;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.math.BigDecimal;
import java.util.Map;
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class ToscaFloatConverter implements PropertyValueConverter {
private static ToscaFloatConverter numberConverter = new ToscaFloatConverter();
- private ToscaFloatConverter() {}
+ private ToscaFloatConverter() {
+ }
public static ToscaFloatConverter getInstance() {
return numberConverter;
@@ -47,5 +46,4 @@ public class ToscaFloatConverter implements PropertyValueConverter {
}
return new BigDecimal(convertedValue).toPlainString();
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverter.java
index 0ce446d3c4..f332dc50eb 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaJsonValueConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,26 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.io.StringReader;
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class ToscaJsonValueConverter extends ToscaValueBaseConverter implements ToscaValueConverter {
- private static ToscaJsonValueConverter toscaJsonConverter = new ToscaJsonValueConverter();
- public static ToscaJsonValueConverter getInstance() {
- return toscaJsonConverter;
- }
+ private static ToscaJsonValueConverter toscaJsonConverter = new ToscaJsonValueConverter();
+ JsonParser jsonParser = new JsonParser();
private ToscaJsonValueConverter() {
-
}
- JsonParser jsonParser = new JsonParser();
+ public static ToscaJsonValueConverter getInstance() {
+ return toscaJsonConverter;
+ }
@Override
public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java
index 8eb4c1099b..4093e9d364 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,35 +17,38 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import com.google.gson.*;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+import org.openecomp.sdc.common.log.wrappers.Logger;
public class ToscaListValueConverter extends ToscaValueBaseConverter implements ToscaValueConverter {
+
+ private static final Logger log = Logger.getLogger(ToscaListValueConverter.class.getName());
private static ToscaListValueConverter listConverter = new ToscaListValueConverter();
private JsonParser jsonParser = new JsonParser();
- private static final Logger log = Logger.getLogger(ToscaListValueConverter.class.getName());
-
- public static ToscaListValueConverter getInstance() {
- return listConverter;
- }
private ToscaListValueConverter() {
+ }
+ public static ToscaListValueConverter getInstance() {
+ return listConverter;
}
@Override
@@ -61,7 +64,6 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements
innerConverter = innerToscaType.getValueConverter();
} else {
DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
-
if (dataTypeDefinition != null) {
ToscaPropertyType toscaPropertyType = null;
if ((toscaPropertyType = isScalarType(dataTypeDefinition)) != null) {
@@ -80,7 +82,6 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements
StringReader reader = new StringReader(value);
JsonReader jsonReader = new JsonReader(reader);
jsonReader.setLenient(true);
-
jsonElement = jsonParser.parse(jsonReader);
} catch (JsonSyntaxException e) {
log.debug("convertToToscaValue failed to parse json value :", e);
@@ -95,7 +96,6 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements
return handleComplexJsonValue(jsonElement);
}
JsonArray asJsonArray = jsonElement.getAsJsonArray();
-
ArrayList<Object> toscaList = new ArrayList<>();
final boolean isScalarF = isScalar;
final ToscaValueConverter innerConverterFinal = innerConverter;
@@ -105,27 +105,22 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements
if (e.isJsonPrimitive()) {
String jsonAsString = e.getAsString();
log.debug("try to convert scalar value {}", jsonAsString);
- convertedValue = innerConverterFinal.convertToToscaValue(jsonAsString, innerType,
- dataTypes);
+ convertedValue = innerConverterFinal.convertToToscaValue(jsonAsString, innerType, dataTypes);
} else {
convertedValue = handleComplexJsonValue(e);
}
-
} else {
JsonObject asJsonObject = e.getAsJsonObject();
Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
-
DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
Map<String, Object> toscaObjectPresentation = new HashMap<>();
-
for (Entry<String, JsonElement> entry : entrySet) {
String propName = entry.getKey();
-
JsonElement elementValue = entry.getValue();
PropertyDefinition propertyDefinition = allProperties.get(propName);
if (propertyDefinition == null) {
- log.debug("The property {} was not found under data type {}",propName,dataTypeDefinition.getName());
+ log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName());
continue;
// return null;
}
@@ -135,8 +130,7 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements
if (propertyType != null) {
if (elementValue.isJsonPrimitive()) {
ToscaValueConverter valueConverter = propertyType.getValueConverter();
- convValue = valueConverter.convertToToscaValue(elementValue.getAsString(), type,
- dataTypes);
+ convValue = valueConverter.convertToToscaValue(elementValue.getAsString(), type, dataTypes);
} else {
if (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(propertyType)) {
ToscaValueConverter valueConverter = propertyType.getValueConverter();
@@ -158,13 +152,10 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements
toscaList.add(convertedValue);
});
return toscaList;
- } catch (
-
- JsonParseException e) {
+ } catch (JsonParseException e) {
log.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter");
return null;
}
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java
index 9e3d371581..1d0354f749 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.converters;
import com.google.gson.JsonArray;
@@ -37,22 +36,21 @@ import java.util.Set;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.model.DataTypeDefinition;
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.common.log.wrappers.Logger;
+import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
public class ToscaMapValueConverter extends ToscaValueBaseConverter implements ToscaValueConverter {
- private static ToscaMapValueConverter mapConverter = new ToscaMapValueConverter();
- private JsonParser jsonParser = new JsonParser();
private static final Logger log = Logger.getLogger(ToscaMapValueConverter.class.getName());
-
- public static ToscaMapValueConverter getInstance() {
- return mapConverter;
- }
+ private static ToscaMapValueConverter mapConverter = new ToscaMapValueConverter();
+ private JsonParser jsonParser = new JsonParser();
private ToscaMapValueConverter() {
+ }
+ public static ToscaMapValueConverter getInstance() {
+ return mapConverter;
}
@Override
@@ -68,7 +66,6 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
if (innerToscaType != null) {
innerConverter = innerToscaType.getValueConverter();
} else {
-
DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
if (dataTypeDefinition != null) {
ToscaPropertyType toscaPropertyType = null;
@@ -78,7 +75,7 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
isScalar = false;
allPropertiesRecursive.addAll(dataTypeDefinition.getProperties());
DataTypeDefinition derivedFrom = dataTypeDefinition.getDerivedFrom();
- while ( !derivedFrom.getName().equals("tosca.datatypes.Root") ){
+ while (!derivedFrom.getName().equals("tosca.datatypes.Root")) {
allPropertiesRecursive.addAll(derivedFrom.getProperties());
derivedFrom = derivedFrom.getDerivedFrom();
}
@@ -87,16 +84,13 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
log.debug("inner Tosca Type is null");
return value;
}
-
}
JsonElement jsonElement = null;
try {
StringReader reader = new StringReader(value);
JsonReader jsonReader = new JsonReader(reader);
jsonReader.setLenient(true);
-
jsonElement = jsonParser.parse(jsonReader);
-
} catch (JsonSyntaxException e) {
log.debug("convertToToscaValue failed to parse json value :", e);
return null;
@@ -107,7 +101,6 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
}
JsonObject asJsonObject = jsonElement.getAsJsonObject();
Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
-
Map<String, Object> toscaMap = new HashMap<>();
final boolean isScalarF = isScalar;
final ToscaValueConverter innerConverterFinal = innerConverter;
@@ -123,8 +116,8 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
}
private void convertEntry(final String innerType, final Map<String, DataTypeDefinition> dataTypes,
- final List<PropertyDefinition> allPropertiesRecursive, final Map<String, Object> toscaMap, final boolean isScalarF,
- final ToscaValueConverter innerConverterFinal, final Entry<String, JsonElement> e) {
+ final List<PropertyDefinition> allPropertiesRecursive, final Map<String, Object> toscaMap, final boolean isScalarF,
+ final ToscaValueConverter innerConverterFinal, final Entry<String, JsonElement> e) {
log.debug("try convert element ");
boolean scalar = isScalarF;
String propType = innerType;
@@ -146,12 +139,12 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
}
}
}
- final Object convertedValue =
- convertDataTypeToToscaObject(propType, dataTypes, innerConverterProp, scalar, e.getValue(), false);
+ final Object convertedValue = convertDataTypeToToscaObject(propType, dataTypes, innerConverterProp, scalar, e.getValue(), false);
toscaMap.put(e.getKey(), convertedValue);
}
- public Object convertDataTypeToToscaObject(String innerType, Map<String, DataTypeDefinition> dataTypes, ToscaValueConverter innerConverter, final boolean isScalarF, JsonElement entryValue, boolean preserveEmptyValue) {
+ public Object convertDataTypeToToscaObject(String innerType, Map<String, DataTypeDefinition> dataTypes, ToscaValueConverter innerConverter,
+ final boolean isScalarF, JsonElement entryValue, boolean preserveEmptyValue) {
Object convertedValue = null;
if (isScalarF && entryValue.isJsonPrimitive()) {
log.debug("try convert scalar value ");
@@ -161,15 +154,13 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
convertedValue = innerConverter.convertToToscaValue(entryValue.getAsString(), innerType, dataTypes);
}
} else {
- if ( entryValue.isJsonPrimitive() ){
+ if (entryValue.isJsonPrimitive()) {
return handleComplexJsonValue(entryValue);
}
-
// ticket 228696523 created / DE272734 / Bug 154492 Fix
- if(entryValue instanceof JsonArray) {
+ if (entryValue instanceof JsonArray) {
ArrayList<Object> toscaObjectPresentationArray = new ArrayList<>();
JsonArray jsonArray = entryValue.getAsJsonArray();
-
for (JsonElement jsonElement : jsonArray) {
Object convertedDataTypeToToscaMap = convertDataTypeToToscaMap(innerType, dataTypes, isScalarF, jsonElement, preserveEmptyValue);
toscaObjectPresentationArray.add(convertedDataTypeToToscaMap);
@@ -182,21 +173,18 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
return convertedValue;
}
- private Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes,
- final boolean isScalarF, JsonElement entryValue, boolean preserveEmptyValue) {
+ private Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes, final boolean isScalarF,
+ JsonElement entryValue, boolean preserveEmptyValue) {
Object convertedValue;
if (entryValue.isJsonPrimitive()) {
return json2JavaPrimitive(entryValue.getAsJsonPrimitive());
}
JsonObject asJsonObjectIn = entryValue.getAsJsonObject();
-
DataTypePropertyConverter.getInstance().mergeDataTypeDefaultValuesWithPropertyValue(asJsonObjectIn, innerType, dataTypes);
Map<String, Object> toscaObjectPresentation = new HashMap<>();
Set<Entry<String, JsonElement>> entrySetIn = asJsonObjectIn.entrySet();
-
for (Entry<String, JsonElement> entry : entrySetIn) {
String propName = entry.getKey();
-
JsonElement elementValue = entry.getValue();
Object convValue;
if (!isScalarF) {
@@ -238,7 +226,7 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
convValue = handleComplexJsonValue(elementValue);
}
}
- if(preserveEmptyValue || !isEmptyObjectValue(convValue) || isGetPolicyValue(propName)){
+ if (preserveEmptyValue || !isEmptyObjectValue(convValue) || isGetPolicyValue(propName)) {
toscaObjectPresentation.put(propName, convValue);
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertor.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertor.java
index 01cf47a124..07bee55416 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertor.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaStringConvertor.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,27 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class ToscaStringConvertor implements ToscaValueConverter {
- private static ToscaStringConvertor stringConverter = new ToscaStringConvertor();
- public static ToscaStringConvertor getInstance() {
- return stringConverter;
- }
+ private static ToscaStringConvertor stringConverter = new ToscaStringConvertor();
private ToscaStringConvertor() {
+ }
+ public static ToscaStringConvertor getInstance() {
+ return stringConverter;
}
@Override
public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
return value;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java
index 366acd3e77..b0598971df 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,63 +17,73 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import com.google.gson.*;
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+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.Set;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.*;
-import java.util.Map.Entry;
-
public class ToscaValueBaseConverter {
- protected Gson gson = new Gson();
+
private static final Logger log = Logger.getLogger(ToscaValueBaseConverter.class.getName());
+ protected Gson gson = new Gson();
- protected Map<String, PropertyDefinition> getAllProperties(DataTypeDefinition dataTypeDefinition) {
+ /**
+ * checks is received Object empty or equals null or not It is relevant only if received Object is instance of String, Map or List class.
+ *
+ * @param convertedValue
+ * @return
+ */
+ public static boolean isEmptyObjectValue(Object convertedValue) {
+ if ((convertedValue == null) || (convertedValue instanceof String && ((String) convertedValue).isEmpty()) || (convertedValue instanceof Map
+ && ((Map) convertedValue).isEmpty()) || (convertedValue instanceof List && ((List) convertedValue).isEmpty())) {
+ return true;
+ }
+ return false;
+ }
+ protected Map<String, PropertyDefinition> getAllProperties(DataTypeDefinition dataTypeDefinition) {
Map<String, PropertyDefinition> allParentsProps = new HashMap<>();
-
while (dataTypeDefinition != null) {
-
List<PropertyDefinition> currentParentsProps = dataTypeDefinition.getProperties();
if (currentParentsProps != null) {
currentParentsProps.stream().forEach(p -> allParentsProps.put(p.getName(), p));
}
-
dataTypeDefinition = dataTypeDefinition.getDerivedFrom();
}
-
return allParentsProps;
}
public ToscaPropertyType isScalarType(DataTypeDefinition dataTypeDef) {
-
ToscaPropertyType result = null;
-
DataTypeDefinition dataType = dataTypeDef;
-
while (dataType != null) {
-
String name = dataType.getName();
ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(name);
if (typeIfScalar != null) {
result = typeIfScalar;
break;
}
-
dataType = dataType.getDerivedFrom();
}
-
return result;
}
public Object handleComplexJsonValue(JsonElement elementValue) {
Object jsonValue = null;
-
Map<String, Object> value = new HashMap<>();
if (elementValue.isJsonObject()) {
JsonObject jsonOb = elementValue.getAsJsonObject();
@@ -106,7 +116,6 @@ public class ToscaValueBaseConverter {
}
}
}
-
return jsonValue;
}
@@ -143,22 +152,4 @@ public class ToscaValueBaseConverter {
throw new IllegalStateException();
}
}
-
- /**
- * checks is received Object empty or equals null or not It is relevant only
- * if received Object is instance of String, Map or List class.
- *
- * @param convertedValue
- * @return
- */
- public static boolean isEmptyObjectValue(Object convertedValue) {
- if ((convertedValue == null)
- || (convertedValue instanceof String && ((String) convertedValue).isEmpty())
- || (convertedValue instanceof Map && ((Map) convertedValue).isEmpty())
- || (convertedValue instanceof List && ((List) convertedValue).isEmpty()))
- {
- return true;
- }
- return false;
- }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueConverter.java
index a9d3cb9544..557817268e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public interface ToscaValueConverter {
- Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes);
+ Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverter.java
index ca0724dfc0..0bfeecb7b5 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueDefaultConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,27 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.converters;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class ToscaValueDefaultConverter implements ToscaValueConverter {
- private static ToscaValueDefaultConverter deafultConverter = new ToscaValueDefaultConverter();
- public static ToscaValueDefaultConverter getInstance() {
- return deafultConverter;
- }
+ private static ToscaValueDefaultConverter deafultConverter = new ToscaValueDefaultConverter();
private ToscaValueDefaultConverter() {
+ }
+ public static ToscaValueDefaultConverter getInstance() {
+ return deafultConverter;
}
@Override
public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
return value;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/BooleanValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/BooleanValidator.java
index 443334db52..b3de6ab054 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/BooleanValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/BooleanValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,29 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Arrays;
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class BooleanValidator implements PropertyTypeValidator {
private static BooleanValidator booleanValidator = new BooleanValidator();
- private static String[] validValues = { "true", "t", "on", "yes", "y", "1", "false", "f", "off", "no", "n", "0" };
-
- public static BooleanValidator getInstance() {
- return booleanValidator;
- }
+ private static String[] validValues = {"true", "t", "on", "yes", "y", "1", "false", "f", "off", "no", "n", "0"};
private BooleanValidator() {
+ }
+ public static BooleanValidator getInstance() {
+ return booleanValidator;
}
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
if (value == null || value.isEmpty()) {
return true;
}
-
return (Arrays.stream(validValues).filter(str -> str.equalsIgnoreCase(value)).toArray().length == 1);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java
index 6ff34671ba..fb4e12c6a4 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
-import com.google.gson.*;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSyntaxException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
@@ -28,72 +36,52 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
public class DataTypeValidatorConverter {
- private static DataTypeValidatorConverter dataTypeValidatorConverter = new DataTypeValidatorConverter();
-
- public static DataTypeValidatorConverter getInstance() {
- return dataTypeValidatorConverter;
- }
-
- private DataTypeValidatorConverter() {
-
- }
-
private static final Logger log = Logger.getLogger(DataTypeValidatorConverter.class.getName());
-
+ private static DataTypeValidatorConverter dataTypeValidatorConverter = new DataTypeValidatorConverter();
JsonParser jsonParser = new JsonParser();
-
ImmutablePair<JsonElement, Boolean> falseResult = new ImmutablePair<>(null, false);
ImmutablePair<JsonElement, Boolean> trueEmptyResult = new ImmutablePair<>(null, true);
-
ImmutablePair<String, Boolean> trueStringEmptyResult = new ImmutablePair<>(null, true);
ImmutablePair<String, Boolean> falseStringEmptyResult = new ImmutablePair<>(null, true);
- private ToscaPropertyType isDataTypeDerviedFromScalarType(DataTypeDefinition dataTypeDef) {
+ private DataTypeValidatorConverter() {
+ }
- ToscaPropertyType result = null;
+ public static DataTypeValidatorConverter getInstance() {
+ return dataTypeValidatorConverter;
+ }
+ private ToscaPropertyType isDataTypeDerviedFromScalarType(DataTypeDefinition dataTypeDef) {
+ ToscaPropertyType result = null;
DataTypeDefinition dataType = dataTypeDef;
-
while (dataType != null) {
-
String name = dataType.getName();
ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(name);
if (typeIfScalar != null) {
result = typeIfScalar;
break;
}
-
dataType = dataType.getDerivedFrom();
}
-
return result;
}
- private ImmutablePair<JsonElement, Boolean> validateAndUpdate(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) {
-
+ private ImmutablePair<JsonElement, Boolean> validateAndUpdate(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition,
+ Map<String, DataTypeDefinition> allDataTypes) {
Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
-
ToscaPropertyType toscaPropertyType = null;
if ((toscaPropertyType = isDataTypeDerviedFromScalarType(dataTypeDefinition)) != null) {
-
PropertyTypeValidator validator = toscaPropertyType.getValidator();
PropertyValueConverter converter = toscaPropertyType.getConverter();
if (jsonElement == null || jsonElement.isJsonNull()) {
boolean valid = validator.isValid(null, null, allDataTypes);
if (!valid) {
- log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName());
+ log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName());
return falseResult;
}
return new ImmutablePair<>(jsonElement, true);
-
} else {
if (jsonElement.isJsonPrimitive()) {
String value = null;
@@ -106,10 +94,10 @@ public class DataTypeValidatorConverter {
}
boolean valid = validator.isValid(value, null, null);
if (!valid) {
- log.trace("Failed in validation of property {} from type {}. Json primitive value is {}", dataTypeDefinition.getName(), dataTypeDefinition.getName(), value);
+ log.trace("Failed in validation of property {} from type {}. Json primitive value is {}", dataTypeDefinition.getName(),
+ dataTypeDefinition.getName(), value);
return falseResult;
}
-
String convertedValue = converter.convert(value, null, allDataTypes);
JsonElement element = null;
try {
@@ -118,46 +106,36 @@ public class DataTypeValidatorConverter {
log.debug("Failed to parse value {} of property {} {}", convertedValue, dataTypeDefinition.getName(), e);
return falseResult;
}
-
return new ImmutablePair<>(element, true);
-
} else {
// MAP, LIST, OTHER types cannot be applied data type
+
// definition scalar type. We currently cannot derived from
- // map/list. (cannot add the entry schema to it)
- log.debug("We cannot derive from list/map. Thus, the value cannot be not primitive since the data type {} is scalar one", dataTypeDefinition.getName());
+ // map/list. (cannot add the entry schema to it)
+ log.debug("We cannot derive from list/map. Thus, the value cannot be not primitive since the data type {} is scalar one",
+ dataTypeDefinition.getName());
return falseResult;
}
}
} else {
-
if (jsonElement == null || jsonElement.isJsonNull()) {
-
return new ImmutablePair<>(jsonElement, true);
-
} else {
-
if (jsonElement.isJsonObject()) {
-
JsonObject buildJsonObject = new JsonObject();
-
JsonObject asJsonObject = jsonElement.getAsJsonObject();
Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
-
for (Entry<String, JsonElement> entry : entrySet) {
String propName = entry.getKey();
-
JsonElement elementValue = entry.getValue();
-
PropertyDefinition propertyDefinition = allProperties.get(propName);
if (propertyDefinition == null) {
- log.debug("The property {} was not found under data type {}" ,propName, dataTypeDefinition.getName());
+ log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName());
return falseResult;
}
String type = propertyDefinition.getType();
boolean isScalarType = ToscaPropertyType.isScalarType(type);
-
if (isScalarType) {
ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type);
if (propertyType == null) {
@@ -175,7 +153,6 @@ public class DataTypeValidatorConverter {
}
}
}
-
String value = null;
if (elementValue != null) {
if (elementValue.isJsonPrimitive() && elementValue.getAsString().isEmpty()) {
@@ -184,16 +161,13 @@ public class DataTypeValidatorConverter {
value = elementValue.toString();
}
}
-
boolean isValid = validator.isValid(value, innerType, allDataTypes);
if (!isValid) {
log.debug("Failed to validate the value {} from type {}", value, propertyType);
return falseResult;
}
-
PropertyValueConverter converter = propertyType.getConverter();
String convertedValue = converter.convert(value, innerType, allDataTypes);
-
JsonElement element = null;
if (convertedValue != null) {
if (convertedValue.isEmpty()) {
@@ -208,67 +182,54 @@ public class DataTypeValidatorConverter {
}
}
buildJsonObject.add(propName, element);
-
} else {
-
DataTypeDefinition typeDefinition = allDataTypes.get(type);
if (typeDefinition == null) {
log.debug("The data type {} cannot be found in the given data type list.", type);
return falseResult;
}
-
ImmutablePair<JsonElement, Boolean> isValid = validateAndUpdate(elementValue, typeDefinition, allDataTypes);
-
if (!isValid.getRight().booleanValue()) {
- log.debug("Failed in validation of value {} from type {}", (elementValue != null ? elementValue.toString() : null), typeDefinition.getName());
+ log.debug("Failed in validation of value {} from type {}", (elementValue != null ? elementValue.toString() : null),
+ typeDefinition.getName());
return falseResult;
}
-
buildJsonObject.add(propName, isValid.getLeft());
}
-
}
-
return new ImmutablePair<>(buildJsonObject, true);
} else {
- log.debug("The value {} of type {} should be json object", (jsonElement != null ? jsonElement.toString() : null), dataTypeDefinition.getName());
+ log.debug("The value {} of type {} should be json object", (jsonElement != null ? jsonElement.toString() : null),
+ dataTypeDefinition.getName());
return falseResult;
}
-
}
}
-
}
- public ImmutablePair<JsonElement, Boolean> validateAndUpdate(String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) {
+ public ImmutablePair<JsonElement, Boolean> validateAndUpdate(String value, DataTypeDefinition dataTypeDefinition,
+ Map<String, DataTypeDefinition> allDataTypes) {
if (value == null || value.isEmpty()) {
return trueEmptyResult;
}
-
JsonElement jsonElement = null;
try {
jsonElement = jsonParser.parse(value);
} catch (JsonSyntaxException e) {
return falseResult;
}
-
return validateAndUpdate(jsonElement, dataTypeDefinition, allDataTypes);
}
private Map<String, PropertyDefinition> getAllProperties(DataTypeDefinition dataTypeDefinition) {
-
Map<String, PropertyDefinition> allParentsProps = new HashMap<>();
-
while (dataTypeDefinition != null) {
-
List<PropertyDefinition> currentParentsProps = dataTypeDefinition.getProperties();
if (currentParentsProps != null) {
currentParentsProps.stream().forEach(p -> allParentsProps.put(p.getName(), p));
}
-
dataTypeDefinition = dataTypeDefinition.getDerivedFrom();
}
-
return allParentsProps;
}
@@ -276,7 +237,6 @@ public class DataTypeValidatorConverter {
if (value == null || value.isEmpty()) {
return true;
}
-
JsonElement jsonElement = null;
try {
jsonElement = jsonParser.parse(value);
@@ -284,17 +244,13 @@ public class DataTypeValidatorConverter {
log.debug("Failed to parse the value {} from type {}", value, dataTypeDefinition, e);
return false;
}
-
return isValid(jsonElement, dataTypeDefinition, allDataTypes);
}
private boolean isValid(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) {
-
Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
-
ToscaPropertyType toscaPropertyType = null;
if ((toscaPropertyType = isDataTypeDerviedFromScalarType(dataTypeDefinition)) != null) {
-
PropertyTypeValidator validator = toscaPropertyType.getValidator();
if (jsonElement == null || jsonElement.isJsonNull()) {
boolean valid = validator.isValid(null, null, allDataTypes);
@@ -302,9 +258,7 @@ public class DataTypeValidatorConverter {
log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName());
return false;
}
-
return true;
-
} else {
if (jsonElement.isJsonPrimitive()) {
String value = null;
@@ -317,39 +271,32 @@ public class DataTypeValidatorConverter {
}
boolean valid = validator.isValid(value, null, allDataTypes);
if (!valid) {
- log.trace("Failed in validation of property {} from type {}. Json primitive value is {}", dataTypeDefinition.getName(), dataTypeDefinition.getName(), value);
+ log.trace("Failed in validation of property {} from type {}. Json primitive value is {}", dataTypeDefinition.getName(),
+ dataTypeDefinition.getName(), value);
return false;
}
-
return true;
-
} else {
// MAP, LIST, OTHER types cannot be applied data type
+
// definition scalar type. We currently cannot derived from
- // map/list. (cannot add the entry schema to it)
- log.debug("We cannot derive from list/map. Thus, the value cannot be not primitive since the data type {} is scalar one", dataTypeDefinition.getName());
+ // map/list. (cannot add the entry schema to it)
+ log.debug("We cannot derive from list/map. Thus, the value cannot be not primitive since the data type {} is scalar one",
+ dataTypeDefinition.getName());
return false;
}
}
} else {
-
if (jsonElement == null || jsonElement.isJsonNull()) {
-
return true;
-
} else {
-
if (jsonElement.isJsonObject()) {
-
JsonObject asJsonObject = jsonElement.getAsJsonObject();
Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
-
for (Entry<String, JsonElement> entry : entrySet) {
String propName = entry.getKey();
-
JsonElement elementValue = entry.getValue();
-
PropertyDefinition propertyDefinition = allProperties.get(propName);
if (propertyDefinition == null) {
log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName());
@@ -357,7 +304,6 @@ public class DataTypeValidatorConverter {
}
String type = propertyDefinition.getType();
boolean isScalarType = ToscaPropertyType.isScalarType(type);
-
if (isScalarType) {
ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type);
if (propertyType == null) {
@@ -375,7 +321,6 @@ public class DataTypeValidatorConverter {
}
}
}
-
String value = null;
if (elementValue != null) {
if (elementValue.isJsonPrimitive() && elementValue.getAsString().isEmpty()) {
@@ -384,40 +329,32 @@ public class DataTypeValidatorConverter {
value = elementValue.toString();
}
}
-
boolean isValid = validator.isValid(value, innerType, allDataTypes);
if (!isValid) {
log.debug("Failed to validate the value {} from type {}", value, propertyType);
return false;
}
-
} else {
-
DataTypeDefinition typeDefinition = allDataTypes.get(type);
if (typeDefinition == null) {
log.debug("The data type {} cannot be found in the given data type list.", type);
return false;
}
-
boolean isValid = isValid(elementValue, typeDefinition, allDataTypes);
-
if (!isValid) {
- log.debug("Failed in validation of value {} from type {}", (elementValue != null ? elementValue.toString() : null), typeDefinition.getName());
+ log.debug("Failed in validation of value {} from type {}", (elementValue != null ? elementValue.toString() : null),
+ typeDefinition.getName());
return false;
}
-
}
-
}
-
return true;
} else {
- log.debug("The value {} of type {} should be json object", (jsonElement != null ? jsonElement.toString() : null), dataTypeDefinition.getName());
+ log.debug("The value {} of type {} should be json object", (jsonElement != null ? jsonElement.toString() : null),
+ dataTypeDefinition.getName());
return false;
}
-
}
}
-
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/FloatValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/FloatValidator.java
index f9121d17ca..4256126e69 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/FloatValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/FloatValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,38 +17,32 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class FloatValidator implements PropertyTypeValidator {
private static FloatValidator FloatValidator = new FloatValidator();
- public static FloatValidator getInstance() {
- return FloatValidator;
- }
-
private FloatValidator() {
+ }
+ public static FloatValidator getInstance() {
+ return FloatValidator;
}
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
if (value == null || value.isEmpty()) {
return true;
}
-
try {
Float.parseFloat(value);
} catch (IllegalArgumentException e) {
return false;
}
-
return true;
}
@@ -56,5 +50,4 @@ public class FloatValidator implements PropertyTypeValidator {
public boolean isValid(String value, String innerType) {
return isValid(value, innerType, null);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatBooleanValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatBooleanValidator.java
index f527206270..72afaccf31 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatBooleanValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatBooleanValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,32 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class HeatBooleanValidator implements PropertyTypeValidator {
private static HeatBooleanValidator booleanValidator = new HeatBooleanValidator();
- public static HeatBooleanValidator getInstance() {
- return booleanValidator;
- }
-
private HeatBooleanValidator() {
+ }
+ public static HeatBooleanValidator getInstance() {
+ return booleanValidator;
}
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
if (value == null || value.isEmpty()) {
return true;
}
-
- if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false") || value.equalsIgnoreCase("t")
- || value.equalsIgnoreCase("f") || value.equalsIgnoreCase("on") || value.equalsIgnoreCase("off")
- || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("no") || value.equalsIgnoreCase("y")
- || value.equalsIgnoreCase("n") || value.equalsIgnoreCase("1") || value.equalsIgnoreCase("0")) {
+ if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false") || value.equalsIgnoreCase("t") || value.equalsIgnoreCase("f") || value
+ .equalsIgnoreCase("on") || value.equalsIgnoreCase("off") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("no") || value
+ .equalsIgnoreCase("y") || value.equalsIgnoreCase("n") || value.equalsIgnoreCase("1") || value.equalsIgnoreCase("0")) {
return true;
}
-
return false;
}
@@ -57,5 +50,4 @@ public class HeatBooleanValidator implements PropertyTypeValidator {
public boolean isValid(String value, String innerType) {
return isValid(value, innerType, null);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatCommaDelimitedListValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatCommaDelimitedListValidator.java
index 6a2a13402b..10480aa655 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatCommaDelimitedListValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatCommaDelimitedListValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
+import java.util.Map;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.common.util.ValidationUtils;
-import java.util.Map;
-
public class HeatCommaDelimitedListValidator implements PropertyTypeValidator {
private static HeatCommaDelimitedListValidator stringValidator = new HeatCommaDelimitedListValidator();
- public static HeatCommaDelimitedListValidator getInstance() {
- return stringValidator;
- }
-
private HeatCommaDelimitedListValidator() {
+ }
+ public static HeatCommaDelimitedListValidator getInstance() {
+ return stringValidator;
}
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
if (value == null || value.isEmpty()) {
return true;
}
-
String coverted = ValidationUtils.removeNoneUtf8Chars(value);
return ValidationUtils.validateIsEnglish(coverted);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java
index 0ae3f74c85..837f90524d 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,33 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class HeatNumberValidator implements PropertyTypeValidator {
private static HeatNumberValidator numberValidator = new HeatNumberValidator();
-
private static FloatValidator floatValidator = FloatValidator.getInstance();
private static IntegerValidator integerValidator = IntegerValidator.getInstance();
- public static HeatNumberValidator getInstance() {
- return numberValidator;
- }
-
private HeatNumberValidator() {
+ }
+ public static HeatNumberValidator getInstance() {
+ return numberValidator;
}
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
if (value == null || value.isEmpty()) {
return true;
}
boolean valid = integerValidator.isValid(value, null, allDataTypes);
-
if (!valid) {
valid = floatValidator.isValid(value, null, allDataTypes);
}
-
return valid;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java
index fd71647b8d..96ee8b0714 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
+import java.util.Map;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.common.util.ValidationUtils;
-import java.util.Map;
-
public class HeatStringValidator implements PropertyTypeValidator {
private static HeatStringValidator stringValidator = new HeatStringValidator();
- public static HeatStringValidator getInstance() {
- return stringValidator;
- }
-
private HeatStringValidator() {
+ }
+ public static HeatStringValidator getInstance() {
+ return stringValidator;
}
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
if (value == null || value.isEmpty()) {
return true;
}
-
String converted = ValidationUtils.removeNoneUtf8Chars(value);
return ValidationUtils.validateIsEnglish(converted);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidator.java
index 484f88e37a..f2745c95ea 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class IntegerValidator implements PropertyTypeValidator {
private static IntegerValidator integerValidator = new IntegerValidator();
+ private PatternBase base8Pattern = new PatternBase(Pattern.compile("([-+])?0o([0-7]+)"), 8);
+ private PatternBase base10Pattern = new PatternBase(Pattern.compile("([-+])?(0|[1-9][0-9]*)"), 10);
+ private PatternBase base16Pattern = new PatternBase(Pattern.compile("([-+])?0x([0-9a-fA-F]+)"), 16);
+ private PatternBase[] patterns = {base10Pattern, base8Pattern, base16Pattern};
private IntegerValidator() {
}
@@ -37,29 +39,11 @@ public class IntegerValidator implements PropertyTypeValidator {
return integerValidator;
}
- private class PatternBase {
- public PatternBase(Pattern pattern, Integer base) {
- this.pattern = pattern;
- this.base = base;
- }
-
- Pattern pattern;
- Integer base;
- }
-
- private PatternBase base8Pattern = new PatternBase(Pattern.compile("([-+])?0o([0-7]+)"), 8);
- private PatternBase base10Pattern = new PatternBase(Pattern.compile("([-+])?(0|[1-9][0-9]*)"), 10);
- private PatternBase base16Pattern = new PatternBase(Pattern.compile("([-+])?0x([0-9a-fA-F]+)"), 16);
-
- private PatternBase[] patterns = { base10Pattern, base8Pattern, base16Pattern };
-
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
if (value == null || value.isEmpty()) {
return true;
}
-
for (PatternBase patternBase : patterns) {
Matcher matcher = patternBase.pattern.matcher(value);
Long parsed = null;
@@ -82,4 +66,15 @@ public class IntegerValidator implements PropertyTypeValidator {
public boolean isValid(String value, String innerType) {
return isValid(value, innerType, null);
}
+
+ private class PatternBase {
+
+ Pattern pattern;
+ Integer base;
+
+ public PatternBase(Pattern pattern, Integer base) {
+ this.pattern = pattern;
+ this.base = base;
+ }
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/JsonValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/JsonValidator.java
index 77fcf5214a..8be4f730ac 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/JsonValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/JsonValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-
import java.io.StringReader;
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.common.log.wrappers.Logger;
public class JsonValidator implements PropertyTypeValidator {
- private static JsonValidator jsonValidator = new JsonValidator();
-
private static final Logger log = Logger.getLogger(JsonValidator.class.getName());
-
+ private static JsonValidator jsonValidator = new JsonValidator();
private static JsonParser jsonParser = new JsonParser();
public static JsonValidator getInstance() {
@@ -43,7 +39,6 @@ public class JsonValidator implements PropertyTypeValidator {
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
if (value == null || value.isEmpty()) {
return true;
}
@@ -57,7 +52,6 @@ public class JsonValidator implements PropertyTypeValidator {
return false;
}
return true;
-
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java
index 07e123376a..86b38fc0b1 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,35 +17,29 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
+import java.util.Map;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.common.util.ValidationUtils;
-import java.util.Map;
-
public class KeyValidator implements PropertyTypeValidator {
public static final int STRING_MAXIMUM_LENGTH = 100;
-
private static KeyValidator keyValidator = new KeyValidator();
- public static KeyValidator getInstance() {
- return keyValidator;
- }
-
private KeyValidator() {
+ }
+ public static KeyValidator getInstance() {
+ return keyValidator;
}
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
if (value == null || value.isEmpty()) {
return false;
}
-
if (value.length() > STRING_MAXIMUM_LENGTH) {
return false;
}
@@ -57,5 +51,4 @@ public class KeyValidator implements PropertyTypeValidator {
public boolean isValid(String value, String innerType) {
return isValid(value, innerType, null);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java
index ac2e6fee73..a069e25f91 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
import com.google.common.base.Strings;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
+import java.util.Map;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.JsonUtils;
-import java.util.Map;
-
public class ListValidator implements PropertyTypeValidator {
- private static ListValidator listValidator = new ListValidator();
-
private static final Logger log = Logger.getLogger(ListValidator.class.getName());
-
+ private static ListValidator listValidator = new ListValidator();
private static JsonParser jsonParser = new JsonParser();
-
private static DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
public static ListValidator getInstance() {
@@ -48,54 +43,47 @@ public class ListValidator implements PropertyTypeValidator {
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
log.debug("Going to validate value {} with inner type {}", value, innerType);
-
if (Strings.isNullOrEmpty(value)) {
return true;
}
if (innerType == null) {
return false;
}
-
PropertyTypeValidator innerValidator;
-
ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
-
if (innerToscaType != null) {
switch (innerToscaType) {
- case STRING:
- innerValidator = ToscaPropertyType.STRING.getValidator();
- break;
- case INTEGER:
- innerValidator = ToscaPropertyType.INTEGER.getValidator();
- break;
- case FLOAT:
- innerValidator = ToscaPropertyType.FLOAT.getValidator();
- break;
- case BOOLEAN:
- innerValidator = ToscaPropertyType.BOOLEAN.getValidator();
- break;
- case JSON:
- innerValidator = ToscaPropertyType.JSON.getValidator();
- break;
- default:
- log.debug("inner Tosca Type is unknown. {}", innerToscaType);
- return false;
+ case STRING:
+ innerValidator = ToscaPropertyType.STRING.getValidator();
+ break;
+ case INTEGER:
+ innerValidator = ToscaPropertyType.INTEGER.getValidator();
+ break;
+ case FLOAT:
+ innerValidator = ToscaPropertyType.FLOAT.getValidator();
+ break;
+ case BOOLEAN:
+ innerValidator = ToscaPropertyType.BOOLEAN.getValidator();
+ break;
+ case JSON:
+ innerValidator = ToscaPropertyType.JSON.getValidator();
+ break;
+ default:
+ log.debug("inner Tosca Type is unknown. {}", innerToscaType);
+ return false;
}
-
} else {
log.debug("inner Tosca Type is: {}", innerType);
-
boolean isValid = validateComplexInnerType(value, innerType, allDataTypes);
- log.debug("Finish to validate value {} of list with inner type {}. result is {}",value,innerType,isValid);
+ log.debug("Finish to validate value {} of list with inner type {}. result is {}", value, innerType, isValid);
return isValid;
}
-
try {
JsonArray jo = (JsonArray) jsonParser.parse(value);
- if(ToscaPropertyType.JSON == innerToscaType)
+ if (ToscaPropertyType.JSON == innerToscaType) {
return true;
+ }
int size = jo.size();
for (int i = 0; i < size; i++) {
JsonElement currentValue = jo.get(i);
@@ -104,17 +92,13 @@ public class ListValidator implements PropertyTypeValidator {
log.debug("validation of element : {} failed", element);
return false;
}
-
}
return true;
-
} catch (Exception e) {
log.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Validator");
}
-
return false;
-
}
@Override
@@ -122,37 +106,30 @@ public class ListValidator implements PropertyTypeValidator {
return isValid(value, innerType, null);
}
- private boolean validateComplexInnerType(String value, String innerType,
- Map<String, DataTypeDefinition> allDataTypes) {
-
+ private boolean validateComplexInnerType(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
DataTypeDefinition innerDataTypeDefinition = allDataTypes.get(innerType);
if (innerDataTypeDefinition == null) {
log.debug("Data type {} cannot be found in our data types.", innerType);
return false;
}
-
try {
-
JsonArray jo = (JsonArray) jsonParser.parse(value);
int size = jo.size();
for (int i = 0; i < size; i++) {
JsonElement currentValue = jo.get(i);
if (currentValue != null) {
String element = JsonUtils.toString(currentValue);
- boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition,
- allDataTypes);
+ boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition, allDataTypes);
if (!isValid) {
- log.debug("Cannot parse value {} from type {} in list parameter",currentValue,innerType);
+ log.debug("Cannot parse value {} from type {} in list parameter", currentValue, innerType);
return false;
}
}
}
-
} catch (Exception e) {
log.debug("Error when parsing JSON of object of type ", e);
return false;
}
-
return true;
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java
index 996e24ee06..406befe50b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java
@@ -17,13 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.model.DataTypeDefinition;
@@ -31,10 +33,6 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.JsonUtils;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
/*
* Property Type Map correct usage:
* null key null value = Yaml reader error
@@ -53,12 +51,9 @@ Keys always need " " around them.
*/
public class MapValidator implements PropertyTypeValidator {
- private static MapValidator mapValidator = new MapValidator();
-
private static final Logger log = Logger.getLogger(MapValidator.class.getName());
-
+ private static MapValidator mapValidator = new MapValidator();
private static DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
-
private static JsonParser jsonParser = new JsonParser();
public static MapValidator getInstance() {
@@ -67,49 +62,42 @@ public class MapValidator implements PropertyTypeValidator {
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
if (StringUtils.isEmpty(value)) {
return true;
}
if (innerType == null) {
return false;
}
-
PropertyTypeValidator innerValidator;
PropertyTypeValidator keyValidator = ToscaPropertyType.KEY.getValidator();
ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType);
-
if (innerToscaType != null) {
switch (innerToscaType) {
- case STRING:
- innerValidator = ToscaPropertyType.STRING.getValidator();
- break;
- case INTEGER:
- innerValidator = ToscaPropertyType.INTEGER.getValidator();
- break;
- case FLOAT:
- innerValidator = ToscaPropertyType.FLOAT.getValidator();
- break;
- case BOOLEAN:
- innerValidator = ToscaPropertyType.BOOLEAN.getValidator();
- break;
- case JSON:
- innerValidator = ToscaPropertyType.JSON.getValidator();
- break;
- default:
- log.debug("inner Tosca Type is unknown. {}", innerToscaType);
- return false;
+ case STRING:
+ innerValidator = ToscaPropertyType.STRING.getValidator();
+ break;
+ case INTEGER:
+ innerValidator = ToscaPropertyType.INTEGER.getValidator();
+ break;
+ case FLOAT:
+ innerValidator = ToscaPropertyType.FLOAT.getValidator();
+ break;
+ case BOOLEAN:
+ innerValidator = ToscaPropertyType.BOOLEAN.getValidator();
+ break;
+ case JSON:
+ innerValidator = ToscaPropertyType.JSON.getValidator();
+ break;
+ default:
+ log.debug("inner Tosca Type is unknown. {}", innerToscaType);
+ return false;
}
-
} else {
log.debug("inner Tosca Type is: {}", innerType);
-
boolean isValid = validateComplexInnerType(value, innerType, allDataTypes);
- log.debug("Finish to validate value {} of map with inner type {}. result is {}",value,innerType,isValid);
+ log.debug("Finish to validate value {} of map with inner type {}. result is {}", value, innerType, isValid);
return isValid;
-
}
-
try {
JsonElement jsonObject = jsonParser.parse(value);
if (!jsonObject.isJsonObject()) {
@@ -121,38 +109,30 @@ public class MapValidator implements PropertyTypeValidator {
log.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Validator");
}
-
return false;
-
}
- private boolean validateJsonObject(Map<String, DataTypeDefinition> allDataTypes, PropertyTypeValidator innerValidator, PropertyTypeValidator keyValidator, JsonObject asJsonObject) {
+ private boolean validateJsonObject(Map<String, DataTypeDefinition> allDataTypes, PropertyTypeValidator innerValidator,
+ PropertyTypeValidator keyValidator, JsonObject asJsonObject) {
Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
for (Entry<String, JsonElement> entry : entrySet) {
String currentKey = entry.getKey();
JsonElement jsonValue = entry.getValue();
-
String element = JsonUtils.toString(jsonValue);
-
- if (!innerValidator.isValid(element, null, allDataTypes)
- || !keyValidator.isValid(entry.getKey(), null, allDataTypes)) {
+ if (!innerValidator.isValid(element, null, allDataTypes) || !keyValidator.isValid(entry.getKey(), null, allDataTypes)) {
log.debug("validation of key : {}, element : {} failed", currentKey, entry.getValue());
return false;
}
}
-
return true;
}
- private boolean validateComplexInnerType(String value, String innerType,
- Map<String, DataTypeDefinition> allDataTypes) {
-
+ private boolean validateComplexInnerType(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
DataTypeDefinition innerDataTypeDefinition = allDataTypes.get(innerType);
if (innerDataTypeDefinition == null) {
log.debug("Data type {} cannot be found in our data types.", innerType);
return false;
}
-
try {
JsonElement jsonObject = jsonParser.parse(value);
JsonObject asJsonObject = jsonObject.getAsJsonObject();
@@ -160,23 +140,19 @@ public class MapValidator implements PropertyTypeValidator {
for (Entry<String, JsonElement> entry : entrySet) {
String currentKey = entry.getKey();
JsonElement currentValue = entry.getValue();
-
if (currentValue != null) {
String element = JsonUtils.toString(currentValue);
- boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition,
- allDataTypes);
+ boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition, allDataTypes);
if (!isValid) {
- log.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey);
+ log.debug("Cannot parse value {} from type {} of key {}", currentValue, innerType, currentKey);
return false;
}
}
}
-
} catch (Exception e) {
log.debug("Cannot parse value {} of map from inner type {}", value, innerType, e);
return false;
}
-
return true;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java
index 587107a93a..5516159ed1 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.validators;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public interface PropertyTypeValidator {
@@ -42,5 +40,4 @@ public interface PropertyTypeValidator {
* "string" - valid tag:yaml.org,2002:str and limited to 100 chars.
*
*/
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java
index cd8d9272f2..4d80dba03f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
+import java.util.Map;
import org.openecomp.sdc.be.config.Configuration.ToscaValidatorsConfig;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
-import java.util.Map;
-
public class StringValidator implements PropertyTypeValidator {
public static final int DEFAULT_STRING_MAXIMUM_LENGTH = 2500;
-
- private static int STRING_MAXIMUM_LENGTH = DEFAULT_STRING_MAXIMUM_LENGTH;
-
private static final Logger log = Logger.getLogger(StringValidator.class.getName());
-
+ private static int STRING_MAXIMUM_LENGTH = DEFAULT_STRING_MAXIMUM_LENGTH;
private static StringValidator stringValidator = new StringValidator();
private StringValidator() {
if (ConfigurationManager.getConfigurationManager() != null) {
- ToscaValidatorsConfig toscaValidators = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getToscaValidators();
+ ToscaValidatorsConfig toscaValidators = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaValidators();
log.debug("toscaValidators= {}", toscaValidators);
if (toscaValidators != null) {
Integer stringMaxLength = toscaValidators.getStringMaxLength();
@@ -58,22 +52,18 @@ public class StringValidator implements PropertyTypeValidator {
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
-
if (value == null || value.isEmpty()) {
return true;
}
-
if (value.length() > STRING_MAXIMUM_LENGTH) {
log.debug("parameter String length {} is higher than configured({})", value.length(), STRING_MAXIMUM_LENGTH);
return false;
}
String converted = ValidationUtils.removeNoneUtf8Chars(value);
boolean isValid = ValidationUtils.validateIsAscii(converted);
-
if (!isValid && log.isDebugEnabled()) {
log.debug("parameter String value {} is not an ascii string.", value.substring(0, Math.min(value.length(), 20)));
}
-
return isValid;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidator.java
index fbec8e8d46..48fcc4cb15 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ToscaBooleanValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,35 +17,29 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.validators;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-
import java.util.Arrays;
import java.util.Map;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
public class ToscaBooleanValidator implements PropertyTypeValidator {
private static ToscaBooleanValidator booleanValidator = new ToscaBooleanValidator();
+ private static String[] validValues = {"true", "on", "yes", "y", "false", "off", "no", "n"};
- private static String[] validValues = { "true", "on", "yes", "y", "false", "off", "no", "n" };
+ private ToscaBooleanValidator() {
+ }
public static ToscaBooleanValidator getInstance() {
return booleanValidator;
}
- private ToscaBooleanValidator() {
-
- }
-
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
-
if (value == null || value.isEmpty()) {
return true;
}
-
return (Arrays.stream(validValues).filter(str -> str.equalsIgnoreCase(value)).toArray().length == 1);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ApplicationVersionException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ApplicationVersionException.java
index 58037192f7..230ebc78f0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ApplicationVersionException.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ApplicationVersionException.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.tosca.version;
import org.openecomp.sdc.be.model.tosca.constraints.exception.TechnicalException;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java
index b0adb52919..448d700862 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.version;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -40,11 +38,18 @@ package org.openecomp.sdc.be.model.tosca.version;
*/
import java.math.BigInteger;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Locale;
+import java.util.Properties;
+import java.util.Stack;
/**
* Generic implementation of version comparison.
- *
+ *
* <p>
* Features:
* <ul>
@@ -72,21 +77,108 @@ import java.util.*;
* something preceded with a dot.</li>
* </ul>
* </p>
- *
- * @see <a href=
- * "https://cwiki.apache.org/confluence/display/MAVENOLD/Versioning">"Versioning"
- * on Maven Wiki</a>
+ *
* @author <a href="mailto:kenney@apache.org">Kenney Westerhof</a>
* @author <a href="mailto:hboutemy@apache.org">Hervé Boutemy</a>
+ * @see <a href= "https://cwiki.apache.org/confluence/display/MAVENOLD/Versioning">"Versioning" on Maven Wiki</a>
*/
public class ComparableVersion implements Comparable<ComparableVersion> {
- private String value;
+ private String value;
private String canonical;
-
private ListItem items;
+ public ComparableVersion(String version) {
+ parseVersion(version);
+ }
+
+ private static Item parseItem(boolean isDigit, String buf) {
+ return isDigit ? new IntegerItem(buf) : new StringItem(buf, false);
+ }
+
+ public final void parseVersion(String version) {
+ this.value = version;
+ items = new ListItem();
+ version = version.toLowerCase(Locale.ENGLISH);
+ ListItem list = items;
+ Stack<Item> stack = new Stack<>();
+ stack.push(list);
+ boolean isDigit = false;
+ int startIndex = 0;
+ for (int i = 0; i < version.length(); i++) {
+ char c = version.charAt(i);
+ if (c == '.') {
+ if (i == startIndex) {
+ list.add(IntegerItem.ZERO);
+ } else {
+ list.add(parseItem(isDigit, version.substring(startIndex, i)));
+ }
+ startIndex = i + 1;
+ } else if (c == '-') {
+ if (i == startIndex) {
+ list.add(IntegerItem.ZERO);
+ } else {
+ list.add(parseItem(isDigit, version.substring(startIndex, i)));
+ }
+ startIndex = i + 1;
+ if (isDigit) {
+ list.normalize(); // 1.0-* = 1-*
+ if ((i + 1 < version.length()) && Character.isDigit(version.charAt(i + 1))) {
+ // new ListItem only if previous were digits and new
+
+ // char is a digit,
+
+ // ie need to differentiate only 1.1 from 1-1
+ list.add(list = new ListItem());
+ stack.push(list);
+ }
+ }
+ } else if (Character.isDigit(c)) {
+ if (!isDigit && i > startIndex) {
+ list.add(new StringItem(version.substring(startIndex, i), true));
+ startIndex = i;
+ }
+ isDigit = true;
+ } else {
+ if (isDigit && i > startIndex) {
+ list.add(parseItem(true, version.substring(startIndex, i)));
+ startIndex = i;
+ }
+ isDigit = false;
+ }
+ }
+ if (version.length() > startIndex) {
+ list.add(parseItem(isDigit, version.substring(startIndex)));
+ }
+ while (!stack.isEmpty()) {
+ list = (ListItem) stack.pop();
+ list.normalize();
+ }
+ canonical = items.toString();
+ }
+
+ @Override
+ public int compareTo(ComparableVersion o) {
+ return items.compareTo(o.items);
+ }
+
+ @Override
+ public String toString() {
+ return value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return (o instanceof ComparableVersion) && canonical.equals(((ComparableVersion) o).canonical);
+ }
+
+ @Override
+ public int hashCode() {
+ return canonical.hashCode();
+ }
+
private interface Item {
+
int INTEGER_ITEM = 0;
int STRING_ITEM = 1;
int LIST_ITEM = 2;
@@ -102,10 +194,11 @@ public class ComparableVersion implements Comparable<ComparableVersion> {
* Represents a numeric item in the version item list.
*/
private static class IntegerItem implements Item {
+
+ public static final IntegerItem ZERO = new IntegerItem();
private static final String INVALID_ITEM = "invalid item: ";
- private static final BigInteger BIG_INTEGER_ZERO = new BigInteger("0");
+ private static final BigInteger BIG_INTEGER_ZERO = new BigInteger("0");
private final BigInteger value;
- public static final IntegerItem ZERO = new IntegerItem();
private IntegerItem() {
this.value = BIG_INTEGER_ZERO;
@@ -129,21 +222,18 @@ public class ComparableVersion implements Comparable<ComparableVersion> {
public int compareTo(Item item) {
if (item == null) {
return BIG_INTEGER_ZERO.equals(value) ? 0 : 1; // 1.0 == 1, 1.1
- // > 1
- }
+ // > 1
+ }
switch (item.getType()) {
- case INTEGER_ITEM:
- return value.compareTo(((IntegerItem) item).value);
-
- case STRING_ITEM:
- return 1; // 1.1 > 1-sp
-
- case LIST_ITEM:
- return 1; // 1.1 > 1-1
-
- default:
- throw new RuntimeException(INVALID_ITEM + item.getClass());
+ case INTEGER_ITEM:
+ return value.compareTo(((IntegerItem) item).value);
+ case STRING_ITEM:
+ return 1; // 1.1 > 1-sp
+ case LIST_ITEM:
+ return 1; // 1.1 > 1-1
+ default:
+ throw new RuntimeException(INVALID_ITEM + item.getClass());
}
}
@@ -157,66 +247,51 @@ public class ComparableVersion implements Comparable<ComparableVersion> {
* Represents a string in the version item list, usually a qualifier.
*/
private static class StringItem implements Item {
- private static final String[] QUALIFIERS = { "alpha", "beta", "milestone", "rc", "snapshot", "", "sp" };
+ private static final String[] QUALIFIERS = {"alpha", "beta", "milestone", "rc", "snapshot", "", "sp"};
private static final List<String> _QUALIFIERS = Arrays.asList(QUALIFIERS);
-
private static final Properties ALIASES = new Properties();
+ /**
+ * A comparable value for the empty-string qualifier. This one is used to determine if a given qualifier makes the version older than one
+ * without a qualifier, or more recent.
+ */
+ private static final String RELEASE_VERSION_INDEX = String.valueOf(_QUALIFIERS.indexOf(""));
+
static {
ALIASES.put("ga", "");
ALIASES.put("final", "");
ALIASES.put("cr", "rc");
}
- /**
- * A comparable value for the empty-string qualifier. This one is used
- * to determine if a given qualifier makes the version older than one
- * without a qualifier, or more recent.
- */
- private static final String RELEASE_VERSION_INDEX = String.valueOf(_QUALIFIERS.indexOf(""));
-
private String value;
public StringItem(String value, boolean followedByDigit) {
if (followedByDigit && value.length() == 1) {
// a1 = alpha-1, b1 = beta-1, m1 = milestone-1
switch (value.charAt(0)) {
- case 'a':
- value = "alpha";
- break;
- case 'b':
- value = "beta";
- break;
- case 'm':
- value = "milestone";
- break;
- default:
- throw new RuntimeException("Invalid item");
+ case 'a':
+ value = "alpha";
+ break;
+ case 'b':
+ value = "beta";
+ break;
+ case 'm':
+ value = "milestone";
+ break;
+ default:
+ throw new RuntimeException("Invalid item");
}
}
this.value = ALIASES.getProperty(value, value);
}
- @Override
- public int getType() {
- return STRING_ITEM;
- }
-
- @Override
- public boolean isNull() {
- return (comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX) == 0);
- }
-
/**
* Returns a comparable value for a qualifier.
- *
- * This method takes into account the ordering of known qualifiers then
- * unknown qualifiers with lexical ordering.
- *
- * just returning an Integer with the index here is faster, but requires
- * a lot of if/then/else to check for -1 or QUALIFIERS.size and then
- * resort to lexical ordering. Most comparisons are decided by the first
- * character, so this is still fast. If more characters are needed then
+ * <p>
+ * This method takes into account the ordering of known qualifiers then unknown qualifiers with lexical ordering.
+ * <p>
+ * just returning an Integer with the index here is faster, but requires a lot of if/then/else to check for -1 or QUALIFIERS.size and then
+ * resort to lexical ordering. Most comparisons are decided by the first character, so this is still fast. If more characters are needed then
* it requires a lexical sort anyway.
*
* @param qualifier
@@ -224,10 +299,19 @@ public class ComparableVersion implements Comparable<ComparableVersion> {
*/
public static String comparableQualifier(String qualifier) {
int i = _QUALIFIERS.indexOf(qualifier);
-
return i == -1 ? (_QUALIFIERS.size() + "-" + qualifier) : String.valueOf(i);
}
+ @Override
+ public int getType() {
+ return STRING_ITEM;
+ }
+
+ @Override
+ public boolean isNull() {
+ return (comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX) == 0);
+ }
+
// @Override
public int compareTo(Item item) {
if (item == null) {
@@ -235,17 +319,14 @@ public class ComparableVersion implements Comparable<ComparableVersion> {
return comparableQualifier(value).compareTo(RELEASE_VERSION_INDEX);
}
switch (item.getType()) {
- case INTEGER_ITEM:
- return -1; // 1.any < 1.1 ?
-
- case STRING_ITEM:
- return comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value));
-
- case LIST_ITEM:
- return -1; // 1.any < 1-1
-
- default:
- throw new RuntimeException("invalid item: " + item.getClass());
+ case INTEGER_ITEM:
+ return -1; // 1.any < 1.1 ?
+ case STRING_ITEM:
+ return comparableQualifier(value).compareTo(comparableQualifier(((StringItem) item).value));
+ case LIST_ITEM:
+ return -1; // 1.any < 1-1
+ default:
+ throw new RuntimeException("invalid item: " + item.getClass());
}
}
@@ -256,8 +337,7 @@ public class ComparableVersion implements Comparable<ComparableVersion> {
}
/**
- * Represents a version list item. This class is used both for the global
- * item list and for sub-lists (which start with '-(number)' in the version
+ * Represents a version list item. This class is used both for the global item list and for sub-lists (which start with '-(number)' in the version
* specification).
*/
private static class ListItem extends ArrayList<Item> implements Item {
@@ -273,11 +353,12 @@ public class ComparableVersion implements Comparable<ComparableVersion> {
}
void normalize() {
- for (ListIterator<Item> iterator = listIterator(size()); iterator.hasPrevious();) {
+ for (ListIterator<Item> iterator = listIterator(size()); iterator.hasPrevious(); ) {
Item item = iterator.previous();
if (item.isNull()) {
iterator.remove(); // remove null trailing items: 0, "",
- // empty list
+
+ // empty list
} else {
break;
}
@@ -294,52 +375,47 @@ public class ComparableVersion implements Comparable<ComparableVersion> {
return first.compareTo(null);
}
switch (item.getType()) {
- case INTEGER_ITEM:
- return -1; // 1-1 < 1.0.x
-
- case STRING_ITEM:
- return 1; // 1-1 > 1-sp
-
- case LIST_ITEM:
- Iterator<Item> left = iterator();
- Iterator<Item> right = ((ListItem) item).iterator();
-
- while (left.hasNext() || right.hasNext()) {
- Item l = left.hasNext() ? left.next() : null;
- Item r = right.hasNext() ? right.next() : null;
-
- int result = 0;
- if (r != null && l != null) {
- result = l.compareTo(r);
- } else if (r == null && l == null) {
- result = 0;
- } else if (l == null) {
- result = -1;
- } else {
- result = 1;
- }
-
- // if this is shorter, then invert the compare and mul with
- // -1
- // int result = (l == null ? (r == null ? 0 : -1 *
- // r.compareTo(l)) : l.compareTo(r));
-
- if (result != 0) {
- return result;
+ case INTEGER_ITEM:
+ return -1; // 1-1 < 1.0.x
+ case STRING_ITEM:
+ return 1; // 1-1 > 1-sp
+ case LIST_ITEM:
+ Iterator<Item> left = iterator();
+ Iterator<Item> right = ((ListItem) item).iterator();
+ while (left.hasNext() || right.hasNext()) {
+ Item l = left.hasNext() ? left.next() : null;
+ Item r = right.hasNext() ? right.next() : null;
+ int result = 0;
+ if (r != null && l != null) {
+ result = l.compareTo(r);
+ } else if (r == null && l == null) {
+ result = 0;
+ } else if (l == null) {
+ result = -1;
+ } else {
+ result = 1;
+ }
+ // if this is shorter, then invert the compare and mul with
+
+ // -1
+
+ // int result = (l == null ? (r == null ? 0 : -1 *
+
+ // r.compareTo(l)) : l.compareTo(r));
+ if (result != 0) {
+ return result;
+ }
}
- }
-
- return 0;
-
- default:
- throw new RuntimeException("invalid item: " + item.getClass());
+ return 0;
+ default:
+ throw new RuntimeException("invalid item: " + item.getClass());
}
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder("(");
- for (Iterator<Item> iter = iterator(); iter.hasNext();) {
+ for (Iterator<Item> iter = iterator(); iter.hasNext(); ) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(',');
@@ -349,107 +425,4 @@ public class ComparableVersion implements Comparable<ComparableVersion> {
return buffer.toString();
}
}
-
- public ComparableVersion(String version) {
- parseVersion(version);
- }
-
- public final void parseVersion(String version) {
- this.value = version;
-
- items = new ListItem();
-
- version = version.toLowerCase(Locale.ENGLISH);
-
- ListItem list = items;
-
- Stack<Item> stack = new Stack<>();
- stack.push(list);
-
- boolean isDigit = false;
-
- int startIndex = 0;
-
- for (int i = 0; i < version.length(); i++) {
- char c = version.charAt(i);
-
- if (c == '.') {
- if (i == startIndex) {
- list.add(IntegerItem.ZERO);
- } else {
- list.add(parseItem(isDigit, version.substring(startIndex, i)));
- }
- startIndex = i + 1;
- } else if (c == '-') {
- if (i == startIndex) {
- list.add(IntegerItem.ZERO);
- } else {
- list.add(parseItem(isDigit, version.substring(startIndex, i)));
- }
- startIndex = i + 1;
-
- if (isDigit) {
- list.normalize(); // 1.0-* = 1-*
-
- if ((i + 1 < version.length()) && Character.isDigit(version.charAt(i + 1))) {
- // new ListItem only if previous were digits and new
- // char is a digit,
- // ie need to differentiate only 1.1 from 1-1
- list.add(list = new ListItem());
-
- stack.push(list);
- }
- }
- } else if (Character.isDigit(c)) {
- if (!isDigit && i > startIndex) {
- list.add(new StringItem(version.substring(startIndex, i), true));
- startIndex = i;
- }
-
- isDigit = true;
- } else {
- if (isDigit && i > startIndex) {
- list.add(parseItem(true, version.substring(startIndex, i)));
- startIndex = i;
- }
-
- isDigit = false;
- }
- }
-
- if (version.length() > startIndex) {
- list.add(parseItem(isDigit, version.substring(startIndex)));
- }
-
- while (!stack.isEmpty()) {
- list = (ListItem) stack.pop();
- list.normalize();
- }
-
- canonical = items.toString();
- }
-
- private static Item parseItem(boolean isDigit, String buf) {
- return isDigit ? new IntegerItem(buf) : new StringItem(buf, false);
- }
-
- @Override
- public int compareTo(ComparableVersion o) {
- return items.compareTo(o.items);
- }
-
- @Override
- public String toString() {
- return value;
- }
-
- @Override
- public boolean equals(Object o) {
- return (o instanceof ComparableVersion) && canonical.equals(((ComparableVersion) o).canonical);
- }
-
- @Override
- public int hashCode() {
- return canonical.hashCode();
- }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/Version.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/Version.java
index 0b71f03599..e6bf32e9d0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/Version.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/Version.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.tosca.version;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -44,26 +42,30 @@ import java.util.regex.Pattern;
/**
* Default implementation of artifact versioning.
- *
+ *
* @author <a href="mailto:brett@apache.org">Brett Porter</a>
*/
public class Version implements Comparable<Version> {
- private Integer majorVersion;
+ private Integer majorVersion;
private Integer minorVersion;
-
private Integer incrementalVersion;
-
private Integer buildNumber;
-
private String qualifier;
-
private ComparableVersion comparable;
public Version(String version) {
parseVersion(version);
}
+ private static Integer getNextIntegerToken(StringTokenizer tok) {
+ String s = tok.nextToken();
+ if ((s.length() > 1) && s.startsWith("0")) {
+ throw new NumberFormatException("Number part has a leading 0: '" + s + "'");
+ }
+ return Integer.valueOf(s);
+ }
+
@Override
public int hashCode() {
return 11 + comparable.hashCode();
@@ -74,11 +76,9 @@ public class Version implements Comparable<Version> {
if (this == other) {
return true;
}
-
if (!(other instanceof Version)) {
return false;
}
-
return compareTo((Version) other) == 0;
}
@@ -108,19 +108,15 @@ public class Version implements Comparable<Version> {
public final void parseVersion(String version) {
comparable = new ComparableVersion(version);
-
int index = version.indexOf("-");
-
String part1;
String part2 = null;
-
if (index < 0) {
part1 = version;
} else {
part1 = version.substring(0, index);
part2 = version.substring(index + 1);
}
-
if (part2 != null) {
try {
if ((part2.length() == 1) || !part2.startsWith("0")) {
@@ -132,7 +128,6 @@ public class Version implements Comparable<Version> {
qualifier = part2;
}
}
-
if ((!part1.contains(".")) && !part1.startsWith("0")) {
try {
majorVersion = Integer.valueOf(part1);
@@ -143,7 +138,6 @@ public class Version implements Comparable<Version> {
}
} else {
boolean fallback = false;
-
StringTokenizer tok = new StringTokenizer(part1, ".");
try {
majorVersion = getNextIntegerToken(tok);
@@ -157,7 +151,6 @@ public class Version implements Comparable<Version> {
qualifier = tok.nextToken();
fallback = Pattern.compile("\\d+").matcher(qualifier).matches();
}
-
// string tokenzier won't detect these and ignores them
if (part1.contains("..") || part1.startsWith(".") || part1.endsWith(".")) {
fallback = true;
@@ -165,7 +158,6 @@ public class Version implements Comparable<Version> {
} catch (NumberFormatException e) {
fallback = true;
}
-
if (fallback) {
// qualifier is the whole version, including "-"
qualifier = version;
@@ -177,14 +169,6 @@ public class Version implements Comparable<Version> {
}
}
- private static Integer getNextIntegerToken(StringTokenizer tok) {
- String s = tok.nextToken();
- if ((s.length() > 1) && s.startsWith("0")) {
- throw new NumberFormatException("Number part has a leading 0: '" + s + "'");
- }
- return Integer.valueOf(s);
- }
-
@Override
public String toString() {
return comparable.toString();
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/ComponentUtilities.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/ComponentUtilities.java
index 7449ca4193..0301f171b5 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/ComponentUtilities.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/ComponentUtilities.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,34 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.utils;
+import static java.util.Collections.emptyList;
+
+import java.util.List;
+import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.be.datatypes.elements.Annotation;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.InputDefinition;
-import java.util.List;
-import java.util.Optional;
-
-import static java.util.Collections.emptyList;
-
public class ComponentUtilities {
+
private ComponentUtilities() {
}
public static Optional<String> getComponentInstanceNameByInstanceId(Component component, String id) {
- return component.getComponentInstanceById(id)
- .flatMap(instance -> component.getComponentInstanceByName(instance.getName()))
- .map(ComponentInstance::getName);
+ return component.getComponentInstanceById(id).flatMap(instance -> component.getComponentInstanceByName(instance.getName()))
+ .map(ComponentInstance::getName);
}
public static List<Annotation> getInputAnnotations(Component component, String inputName) {
- return getInputByName(component, inputName)
- .map(InputDefinition::getAnnotations)
- .orElse(emptyList());
+ return getInputByName(component, inputName).map(InputDefinition::getAnnotations).orElse(emptyList());
}
private static Optional<InputDefinition> getInputByName(Component component, String inputName) {
- return component.safeGetInputs().stream()
- .filter(input -> input.getName().equals(inputName))
- .findFirst();
+ return component.safeGetInputs().stream().filter(input -> input.getName().equals(inputName)).findFirst();
}
public static boolean isNotUpdatedCapReqName(String prefix, String currName, String previousName) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/GroupUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/GroupUtils.java
index 7b396cbdda..8c8362476c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/GroupUtils.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/GroupUtils.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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.model.utils;
import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
@@ -27,59 +26,48 @@ import org.springframework.util.StringUtils;
public class GroupUtils {
- public static boolean isVfModule(String type) {
- return type.equals(Constants.DEFAULT_GROUP_VF_MODULE);
- }
-
- /**
+ public static boolean isVfModule(String type) {
+ return type.equals(Constants.DEFAULT_GROUP_VF_MODULE);
+ }
+
+ /**
* The version of the group/poloces is an integer. In order to support BC, we might get a version in a float format.
*
* @param promoteVersion
* @return
*/
-
- public static String updateVersion(PromoteVersionEnum promoteVersion, String currentVesion) {
- if(StringUtils.isEmpty(currentVesion)){
- return "0.0";
- }
+ public static String updateVersion(PromoteVersionEnum promoteVersion, String currentVesion) {
+ if (StringUtils.isEmpty(currentVesion)) {
+ return "0.0";
+ }
String newVersion = currentVesion;
- switch (promoteVersion){
- case MINOR:
- newVersion = GroupUtils.increaseMainorVersion(currentVesion);
- break;
- case MAJOR:
- newVersion = GroupUtils.increaseMajorVersion(currentVesion);
- break;
- default:
- break;
- }
- return newVersion;
+ switch (promoteVersion) {
+ case MINOR:
+ newVersion = GroupUtils.increaseMainorVersion(currentVesion);
+ break;
+ case MAJOR:
+ newVersion = GroupUtils.increaseMajorVersion(currentVesion);
+ break;
+ default:
+ break;
+ }
+ return newVersion;
}
-
- private static String increaseMajorVersion(String version) {
-
- String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMITER_REGEXP);
- Integer majorVersion = Integer.parseInt(versionParts[0]);
-
-
- Integer mainorVersion = versionParts.length > 1?Integer.parseInt(versionParts[1]):0;
-
- if(mainorVersion > 0 || majorVersion == 0){
- majorVersion++;
- }
- return String.valueOf(majorVersion);
-
- }
-
- private static String increaseMainorVersion(String version) {
- String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMITER_REGEXP);
-
- Integer mainorVersion = versionParts.length > 1?Integer.parseInt(versionParts[1]):0;
-
- mainorVersion++;
-
- return versionParts[0] + ToscaElementLifecycleOperation.VERSION_DELIMITER + String.valueOf(mainorVersion);
+ private static String increaseMajorVersion(String version) {
+ String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMITER_REGEXP);
+ Integer majorVersion = Integer.parseInt(versionParts[0]);
+ Integer mainorVersion = versionParts.length > 1 ? Integer.parseInt(versionParts[1]) : 0;
+ if (mainorVersion > 0 || majorVersion == 0) {
+ majorVersion++;
+ }
+ return String.valueOf(majorVersion);
+ }
- }
+ private static String increaseMainorVersion(String version) {
+ String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMITER_REGEXP);
+ Integer mainorVersion = versionParts.length > 1 ? Integer.parseInt(versionParts[1]) : 0;
+ mainorVersion++;
+ return versionParts[0] + ToscaElementLifecycleOperation.VERSION_DELIMITER + String.valueOf(mainorVersion);
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/TypeCompareUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/TypeCompareUtils.java
index b850a466a3..dd2575234b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/TypeCompareUtils.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/TypeCompareUtils.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, 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,38 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.model.utils;
+import static org.springframework.util.CollectionUtils.isEmpty;
+
import com.google.common.base.Strings;
import fj.data.Either;
-import org.apache.commons.collections.SetUtils;
-import org.openecomp.sdc.be.dao.utils.MapUtil;
-import org.openecomp.sdc.be.model.*;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
-
-import static org.springframework.util.CollectionUtils.isEmpty;
-
+import org.apache.commons.collections.SetUtils;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.GroupTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.RelationshipTypeDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
/**
- * Types comparison utils
- * The class is required since origin class "equals" methods
- * take in account fields that should be ignored during update of that types.
- * @author dr2032
+ * Types comparison utils The class is required since origin class "equals" methods take in account fields that should be ignored during update of
+ * that types.
*
+ * @author dr2032
*/
public class TypeCompareUtils {
private TypeCompareUtils() {
}
-
+
public static <R> Either<R, StorageOperationStatus> typeAlreadyExists() {
return Either.right(StorageOperationStatus.OK);
}
@@ -59,95 +60,69 @@ public class TypeCompareUtils {
if (gt1 == null || gt2 == null) {
return false;
}
-
/*
* We compare here attributes, capabilities and not inherited properties of group types.
* So even if properties of group type parent were changed it will not effect on comparison of these group types.
*/
- return Objects.equals(gt1.getType(), gt2.getType()) &&
- Objects.equals(gt1.getName(), gt2.getName()) &&
- Objects.equals(gt1.getIcon(), gt2.getIcon()) &&
- Objects.equals(gt1.getVersion(), gt2.getVersion()) &&
- Objects.equals(gt1.getDerivedFrom(), gt2.getDerivedFrom()) &&
- Objects.equals(gt1.getMembers(), gt2.getMembers()) &&
- Objects.equals(gt1.getMetadata(), gt2.getMetadata()) &&
- capabilitiesEqual(gt1.getCapabilities(), gt2.getCapabilities()) &&
- propertiesEquals(collectNotInheritedProperties(gt1.getProperties(), gt1.getUniqueId()),
- collectNotInheritedProperties(gt2.getProperties(), gt2.getUniqueId()));
+ return Objects.equals(gt1.getType(), gt2.getType()) && Objects.equals(gt1.getName(), gt2.getName()) && Objects
+ .equals(gt1.getIcon(), gt2.getIcon()) && Objects.equals(gt1.getVersion(), gt2.getVersion()) && Objects
+ .equals(gt1.getDerivedFrom(), gt2.getDerivedFrom()) && Objects.equals(gt1.getMembers(), gt2.getMembers()) && Objects
+ .equals(gt1.getMetadata(), gt2.getMetadata()) && capabilitiesEqual(gt1.getCapabilities(), gt2.getCapabilities()) && propertiesEquals(
+ collectNotInheritedProperties(gt1.getProperties(), gt1.getUniqueId()),
+ collectNotInheritedProperties(gt2.getProperties(), gt2.getUniqueId()));
}
-
+
public static boolean isCapabilityTypesEquals(CapabilityTypeDefinition ct1, CapabilityTypeDefinition ct2) {
if (ct1 == ct2) {
return true;
}
-
if (ct1 == null || ct2 == null) {
return false;
}
-
- return Objects.equals(ct1.getType(), ct2.getType()) &&
- Objects.equals(ct1.getDerivedFrom(), ct2.getDerivedFrom()) &&
- Objects.equals(ct1.getDescription(), ct2.getDescription()) &&
- SetUtils.isEqualSet(ct1.getValidSourceTypes(), ct2.getValidSourceTypes()) &&
- propertiesEquals(ct1.getProperties(), ct2.getProperties());
+ return Objects.equals(ct1.getType(), ct2.getType()) && Objects.equals(ct1.getDerivedFrom(), ct2.getDerivedFrom()) && Objects
+ .equals(ct1.getDescription(), ct2.getDescription()) && SetUtils.isEqualSet(ct1.getValidSourceTypes(), ct2.getValidSourceTypes())
+ && propertiesEquals(ct1.getProperties(), ct2.getProperties());
}
public static boolean isRelationshipTypesEquals(RelationshipTypeDefinition rs1, RelationshipTypeDefinition rs2) {
if (rs1 == rs2) {
return true;
}
-
if (rs1 == null || rs2 == null) {
return false;
}
-
- return Objects.equals(rs1.getType(), rs2.getType()) &&
- Objects.equals(rs1.getDerivedFrom(), rs2.getDerivedFrom()) &&
- Objects.equals(rs1.getDescription(), rs2.getDescription()) &&
- SetUtils.isEqualSet(rs1.getValidSourceTypes(), rs2.getValidSourceTypes()) &&
- propertiesEquals(rs1.getProperties(), rs2.getProperties());
+ return Objects.equals(rs1.getType(), rs2.getType()) && Objects.equals(rs1.getDerivedFrom(), rs2.getDerivedFrom()) && Objects
+ .equals(rs1.getDescription(), rs2.getDescription()) && SetUtils.isEqualSet(rs1.getValidSourceTypes(), rs2.getValidSourceTypes())
+ && propertiesEquals(rs1.getProperties(), rs2.getProperties());
}
-
+
private static boolean propertiesEquals(Map<String, PropertyDefinition> props1, Map<String, PropertyDefinition> props2) {
if (props1 == props2) {
return true;
}
-
if (isEmpty(props1) && isEmpty(props2)) {
return true;
- }
- else if(props1 == null || props2 == null) {
+ } else if (props1 == null || props2 == null) {
return false;
- }
- else if(props1.size() != props2.size())
- {
+ } else if (props1.size() != props2.size()) {
return false;
}
-
- return props2.entrySet().stream()
- .allMatch(entry -> propertyEquals(props1.get(entry.getKey()), entry.getValue()));
-
+ return props2.entrySet().stream().allMatch(entry -> propertyEquals(props1.get(entry.getKey()), entry.getValue()));
}
-
+
public static boolean propertiesEquals(List<PropertyDefinition> props1, List<PropertyDefinition> props2) {
if (props1 == props2) {
return true;
}
-
if (isEmpty(props1) && isEmpty(props2)) {
return true;
- }
- else if(props1 == null || props2 == null) {
+ } else if (props1 == null || props2 == null) {
return false;
- }
- else if(props1.size() != props2.size())
- {
+ } else if (props1.size() != props2.size()) {
return false;
}
-
Map<String, PropertyDefinition> pt1PropsByName = MapUtil.toMap(props1, PropertyDefinition::getName);
- return props2.stream()
- .allMatch(pt2Prop -> propertyEquals(pt1PropsByName.get(pt2Prop.getName()), pt2Prop));
+ return props2.stream().allMatch(pt2Prop -> propertyEquals(pt1PropsByName.get(pt2Prop.getName()), pt2Prop));
}
private static boolean propertyEquals(PropertyDefinition prop1, PropertyDefinition prop2) {
@@ -157,43 +132,32 @@ public class TypeCompareUtils {
if (prop1 == null || prop2 == null) {
return false;
}
- return Objects.equals(prop1.getDefaultValue(), prop2.getDefaultValue()) &&
- prop1.isDefinition() == prop2.isDefinition() &&
- Objects.equals(prop1.getDescription(), prop2.getDescription()) &&
- prop1.isPassword() == prop2.isPassword() &&
- prop1.isRequired() == prop2.isRequired() &&
- Objects.equals(prop1.getSchemaType(), prop2.getSchemaType()) &&
- Objects.equals(prop1.getType(), prop2.getType());
+ return Objects.equals(prop1.getDefaultValue(), prop2.getDefaultValue()) && prop1.isDefinition() == prop2.isDefinition() && Objects
+ .equals(prop1.getDescription(), prop2.getDescription()) && prop1.isPassword() == prop2.isPassword() && prop1.isRequired() == prop2
+ .isRequired() && Objects.equals(prop1.getSchemaType(), prop2.getSchemaType()) && Objects.equals(prop1.getType(), prop2.getType());
}
- private static boolean capabilitiesEqual(Map<String, CapabilityDefinition> caps1, Map<String, CapabilityDefinition> caps2) {
+ private static boolean capabilitiesEqual(Map<String, CapabilityDefinition> caps1, Map<String, CapabilityDefinition> caps2) {
if (caps1 == caps2) {
return true;
}
-
if (caps1 == null || caps2 == null) {
return false;
}
-
- if(caps1.size() != caps2.size()) {
+ if (caps1.size() != caps2.size()) {
return false;
}
-
- return caps2.entrySet().stream()
- .allMatch(capEntry2 -> capabilityEquals(caps1.get(capEntry2.getKey()), capEntry2.getValue()));
+ return caps2.entrySet().stream().allMatch(capEntry2 -> capabilityEquals(caps1.get(capEntry2.getKey()), capEntry2.getValue()));
}
public static boolean capabilityEquals(CapabilityDefinition capDef1, CapabilityDefinition capDef2) {
- return Objects.equals(capDef1.getName(), capDef2.getName()) &&
- Objects.equals(capDef1.getType(), capDef2.getType()) &&
- Objects.equals(capDef1.getDescription(), capDef2.getDescription()) &&
- propValuesEqual(capDef1.getProperties(), capDef2.getProperties());
+ return Objects.equals(capDef1.getName(), capDef2.getName()) && Objects.equals(capDef1.getType(), capDef2.getType()) && Objects
+ .equals(capDef1.getDescription(), capDef2.getDescription()) && propValuesEqual(capDef1.getProperties(), capDef2.getProperties());
}
private static boolean propValuesEqual(final List<ComponentInstanceProperty> props1, final List<ComponentInstanceProperty> props2) {
Map<String, String> propValues1 = toValueMap(props1);
Map<String, String> propValues2 = toValueMap(props2);
-
return propValues1.equals(propValues2);
}
@@ -202,42 +166,34 @@ public class TypeCompareUtils {
* @return
*/
private static Map<String, String> toValueMap(final List<ComponentInstanceProperty> props) {
- return props.stream()
- .filter(TypeCompareUtils::isCapabilityPropValue)
- .collect(Collectors.toMap(ComponentInstanceProperty::getName, p -> p.getValue() != null? p.getValue(): ""));
+ return props.stream().filter(TypeCompareUtils::isCapabilityPropValue)
+ .collect(Collectors.toMap(ComponentInstanceProperty::getName, p -> p.getValue() != null ? p.getValue() : ""));
}
-
+
/**
* Returns true if the property object was created from property value or false otherwise
- *
- * We try to segregate original properties values from dummy ones created from relevant properties.
- * Such dummy property value doesn't have their valueUniqueId but it has uniqueId taken from property.
- *
+ * <p>
+ * We try to segregate original properties values from dummy ones created from relevant properties. Such dummy property value doesn't have their
+ * valueUniqueId but it has uniqueId taken from property.
+ *
* @param property
* @return
*/
private static boolean isCapabilityPropValue(ComponentInstanceProperty property) {
return property.getValueUniqueUid() != null || property.getUniqueId() == null;
}
-
+
/**
* Collect properties of resource that belongs to it without taking in account properties inherited from resource parents.
*/
- private static List<PropertyDefinition> collectNotInheritedProperties(List<PropertyDefinition> properties,
- String resourceId) {
+ private static List<PropertyDefinition> collectNotInheritedProperties(List<PropertyDefinition> properties, String resourceId) {
if (Strings.isNullOrEmpty(resourceId)) {
return properties;
}
-
- return properties.stream()
- .filter(prop-> !isInherited(prop, resourceId))
- .collect(Collectors.toList());
+ return properties.stream().filter(prop -> !isInherited(prop, resourceId)).collect(Collectors.toList());
}
-
-
+
private static boolean isInherited(PropertyDefinition prop, String resourceId) {
- return prop.getUniqueId() != null &&
- !prop.getUniqueId().equals(UniqueIdBuilder.buildPropertyUniqueId(resourceId, prop.getName()));
+ return prop.getUniqueId() != null && !prop.getUniqueId().equals(UniqueIdBuilder.buildPropertyUniqueId(resourceId, prop.getName()));
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/OperationUi.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/OperationUi.java
index e5c2074c0c..d80e1cba00 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/OperationUi.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/OperationUi.java
@@ -16,7 +16,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.ui.model;
import java.util.ArrayList;
@@ -39,5 +38,4 @@ public class OperationUi {
}
inputs.add(input);
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/PropertyAssignmentUi.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/PropertyAssignmentUi.java
index de6265b3e8..17ced923cb 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/PropertyAssignmentUi.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/PropertyAssignmentUi.java
@@ -16,7 +16,6 @@
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.ui.model;
import lombok.Getter;
@@ -25,6 +24,7 @@ import lombok.Setter;
@Getter
@Setter
public class PropertyAssignmentUi {
+
private String name;
private String value;
private String type;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/SerializedHashMap.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/SerializedHashMap.java
index 5e73ee95e2..50cdb13f98 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/SerializedHashMap.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/SerializedHashMap.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.ui.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UIConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UIConstraint.java
index 779dfbe289..5618b3d478 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UIConstraint.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UIConstraint.java
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.openecomp.sdc.be.ui.model;
import java.io.Serializable;
@@ -45,13 +44,11 @@ public class UIConstraint implements Serializable {
this.value = value;
}
- public UIConstraint(String servicePropertyName, String constraintOperator, String sourceType, String sourceName,
- Object value) {
+ public UIConstraint(String servicePropertyName, String constraintOperator, String sourceType, String sourceName, Object value) {
this.servicePropertyName = servicePropertyName;
this.constraintOperator = constraintOperator;
this.sourceType = sourceType;
this.sourceName = sourceName;
this.value = value;
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java
index 99c0d33b17..ac5ab7c23a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.ui.model;
import java.util.List;
@@ -32,5 +31,4 @@ public class UiCategories {
private List<CategoryDefinition> resourceCategories;
private List<CategoryDefinition> serviceCategories;
private List<CategoryDefinition> productCategories;
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCombination.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCombination.java
index 952f3b1ff8..995b12ed48 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCombination.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCombination.java
@@ -15,7 +15,6 @@
*
*
*/
-
package org.openecomp.sdc.be.ui.model;
import lombok.AllArgsConstructor;
@@ -27,5 +26,4 @@ public class UiCombination {
private final String name;
private final String description;
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java
index c7e34fcbfa..f9741fc234 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java
@@ -17,10 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.ui.model;
-
import java.util.List;
import java.util.Map;
import lombok.Getter;
@@ -74,14 +72,11 @@ public class UiComponentDataTransfer {
private List<OutputDefinition> outputs;
private List<GroupDefinition> groups;
private Map<String, InterfaceDefinition> interfaces;
-
private Map<String, CINodeFilterDataDefinition> nodeFilter;
private Map<String, SubstitutionFilterDataDefinition> substitutionFilter;
-
private Map<String, UINodeFilter> nodeFilterforNode;
private Map<String, UINodeFilter> substitutionFilterForTopologyTemplate;
private List<PropertyDefinition> properties;
private List<AttributeDefinition> attributes;
private Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces;
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java
index 2a7c036d3e..09cee8bc2c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.ui.model;
import java.util.List;
@@ -33,58 +32,33 @@ import org.openecomp.sdc.be.model.category.CategoryDefinition;
public abstract class UiComponentMetadata {
private String uniqueId;
-
private String name; // archiveName
private String version; // archiveVersion
-
private Boolean isHighestVersion;
-
private Long creationDate;
private Long lastUpdateDate;
-
private String description;
-
private String lifecycleState;
-
private List<String> tags;
-
private String icon;
-
private String UUID;
-
private String normalizedName;
-
private String systemName;
-
private String contactId;
-
private Map<String, String> allVersions;
-
private Boolean isDeleted;
-
private String projectCode;
-
private String csarUUID;
-
private String csarVersion;
-
private String importedToscaChecksum;
-
private String invariantUUID;
-
private ComponentTypeEnum componentType;
-
private List<CategoryDefinition> categories;
-
private String creatorUserId;
-
private String creatorFullName;
-
private String lastUpdaterUserId;
-
private String lastUpdaterFullName;
-
//Archive/Restore
private Boolean isArchived;
private Long archiveTime;
@@ -94,7 +68,6 @@ public abstract class UiComponentMetadata {
}
public UiComponentMetadata(List<CategoryDefinition> categories, ComponentMetadataDataDefinition metadata) {
-
this.uniqueId = metadata.getUniqueId();
this.name = metadata.getName(); // archiveName
this.version = metadata.getVersion();
@@ -121,11 +94,9 @@ public abstract class UiComponentMetadata {
this.creatorFullName = metadata.getCreatorFullName();
this.lastUpdaterFullName = metadata.getLastUpdaterFullName();
this.lastUpdaterUserId = metadata.getLastUpdaterUserId();
-
//archive
this.isArchived = metadata.isArchived();
this.archiveTime = metadata.getArchiveTime();
this.isVspArchived = metadata.isVspArchived();
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiLeftPaletteComponent.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiLeftPaletteComponent.java
index bea1e1790c..83d8571384 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiLeftPaletteComponent.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiLeftPaletteComponent.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.ui.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -35,6 +34,7 @@ public class UiLeftPaletteComponent implements ICategorizedElement {
private final String uniqueId;
private final String name; // archiveName
+
private final String version; // archiveVersion
private final String description;
private final List<String> tags;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java
index eabb2cde14..f50bbf69e3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.ui.model;
import java.util.List;
@@ -35,17 +34,10 @@ import org.openecomp.sdc.be.model.PropertyDefinition;
public class UiResourceDataTransfer extends UiComponentDataTransfer {
private UiResourceMetadata metadata;
-
private List<String> derivedFrom;
-
private List<String> derivedList;
-
private List<PropertyDefinition> properties;
-
private List<AttributeDefinition> attributes;
-
private Map<String, InterfaceDefinition> interfaces;
-
private List<String> defaultCapabilities;
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java
index 971f966d5f..b8fcc40158 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.ui.model;
import java.util.List;
@@ -45,9 +44,7 @@ public class UiResourceMetadata extends UiComponentMetadata {
private List<String> derivedFrom;
private Map<String, String> categorySpecificMetadata;
-
- public UiResourceMetadata(List<CategoryDefinition> categories, List<String> derivedFrom,
- ResourceMetadataDataDefinition metadata) {
+ public UiResourceMetadata(List<CategoryDefinition> categories, List<String> derivedFrom, ResourceMetadataDataDefinition metadata) {
super(categories, metadata);
this.vendorName = metadata.getVendorName();
this.vendorRelease = metadata.getVendorRelease();
@@ -59,8 +56,4 @@ public class UiResourceMetadata extends UiComponentMetadata {
this.derivedFrom = derivedFrom;
this.categorySpecificMetadata = metadata.getCategorySpecificMetadata();
}
-
}
-
-
-
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java
index cee7cf04ca..5f2b047668 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.ui.model;
import java.util.Map;
@@ -35,5 +34,4 @@ public class UiServiceDataTransfer extends UiComponentDataTransfer {
private Map<String, ArtifactDefinition> serviceApiArtifacts;
private Map<String, ForwardingPathDataDefinition> forwardingPaths;
private UiServiceMetadata metadata;
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java
index 6aec7bca36..e6c0a2d7ae 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java
@@ -17,7 +17,6 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.ui.model;
import java.util.List;
@@ -53,5 +52,4 @@ public class UiServiceMetadata extends UiComponentMetadata {
this.serviceFunction = metadata.getServiceFunction();
this.categorySpecificMetadata = metadata.getCategorySpecificMetadata();
}
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java
index 79f5b80953..56c1ae6ffc 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,27 +17,36 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.unittests.utils;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.*;
-import org.openecomp.sdc.be.resources.data.*;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.resources.data.CapabilityData;
+import org.openecomp.sdc.be.resources.data.CapabilityInstData;
+import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
+import org.openecomp.sdc.be.resources.data.RequirementData;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
public final class FactoryUtils {
+
private static final String STRING = "string";
private static final String DEFAULT_CAPABILITY_TYPE = "tosca.capabilities.Node";
- private FactoryUtils() {
+ private FactoryUtils() {
}
public static Resource createVFWithRI(String riVersion) {
@@ -59,13 +68,12 @@ public final class FactoryUtils {
String uniqueId = UUID.randomUUID().toString();
resource.getMetadataDataDefinition().setHighestVersion(true);
resource.getMetadataDataDefinition().setUniqueId(uniqueId);
- ((ResourceMetadataDataDefinition)resource.getMetadataDataDefinition()).setResourceType(ResourceTypeEnum.getTypeIgnoreCase(resourceType));
+ ((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).setResourceType(ResourceTypeEnum.getTypeIgnoreCase(resourceType));
return resource;
}
public static void addComponentInstanceToVF(Resource vf, ComponentInstance resourceInstance) {
- List<ComponentInstance> componentsInstances = vf.getComponentInstances() != null ? vf.getComponentInstances()
- : new ArrayList<>();
+ List<ComponentInstance> componentsInstances = vf.getComponentInstances() != null ? vf.getComponentInstances() : new ArrayList<>();
componentsInstances.add(resourceInstance);
vf.setComponentInstances(componentsInstances);
}
@@ -79,7 +87,6 @@ public final class FactoryUtils {
ri.setName("genericRI" + uniqueId);
ri.setOriginType(OriginTypeEnum.VF);
return ri;
-
}
public static ComponentInstance createResourceInstanceWithVersion(String riVersion) {
@@ -92,7 +99,6 @@ public final class FactoryUtils {
CapabilityData capData = new CapabilityData();
String uniqueId = UUID.randomUUID().toString();
capData.setUniqueId(uniqueId);
-
capData.setType(DEFAULT_CAPABILITY_TYPE);
return capData;
}
@@ -104,8 +110,7 @@ public final class FactoryUtils {
return reqData;
}
- public static CapabilityDefinition convertCapabilityDataToCapabilityDefinitionAddProperties(
- CapabilityData capData) {
+ public static CapabilityDefinition convertCapabilityDataToCapabilityDefinitionAddProperties(CapabilityData capData) {
CapabilityDefinition capDef = new CapabilityDefinition();
capDef.setName("Cap2");
capDef.setDescription(capData.getDescription());
@@ -118,22 +123,18 @@ public final class FactoryUtils {
host.setName("host");
host.setDefaultValue("defhost");
host.setType(STRING);
-
host.setSchema(new SchemaDefinition());
host.getSchema().setProperty(new PropertyDataDefinition());
host.getSchema().getProperty().setType(STRING);
-
capDef.getProperties().add(host);
ComponentInstanceProperty port = new ComponentInstanceProperty();
port.setName("port");
port.setDefaultValue("defport");
port.setUniqueId(UUID.randomUUID().toString());
port.setType(STRING);
-
port.setSchema(new SchemaDefinition());
port.getSchema().setProperty(new PropertyDataDefinition());
port.getSchema().getProperty().setType(STRING);
-
capDef.getProperties().add(port);
return capDef;
}
@@ -145,22 +146,18 @@ public final class FactoryUtils {
host.setName("host");
host.setValue("newhost");
host.setType(STRING);
-
host.setSchema(new SchemaDefinition());
host.getSchema().setProperty(new PropertyDataDefinition());
host.getSchema().getProperty().setType(STRING);
-
properties.add(host);
ComponentInstanceProperty port = new ComponentInstanceProperty();
port.setName("port");
port.setValue("newport");
port.setUniqueId(UUID.randomUUID().toString());
port.setType(STRING);
-
port.setSchema(new SchemaDefinition());
port.getSchema().setProperty(new PropertyDataDefinition());
port.getSchema().getProperty().setType(STRING);
-
properties.add(port);
return properties;
}
@@ -211,22 +208,18 @@ public final class FactoryUtils {
host.setName("host");
host.setDefaultValue("roothost");
host.setType(STRING);
-
host.setSchema(new SchemaDefinition());
host.getSchema().setProperty(new PropertyDataDefinition());
host.getSchema().getProperty().setType(STRING);
-
capDef.getProperties().add(host);
ComponentInstanceProperty port = new ComponentInstanceProperty();
port.setName("port");
port.setDefaultValue("rootport");
port.setUniqueId(UUID.randomUUID().toString());
port.setType(STRING);
-
port.setSchema(new SchemaDefinition());
port.getSchema().setProperty(new PropertyDataDefinition());
port.getSchema().getProperty().setType(STRING);
-
capDef.getProperties().add(port);
return capDef;
}