summaryrefslogtreecommitdiffstats
path: root/catalog-dao/src
diff options
context:
space:
mode:
Diffstat (limited to 'catalog-dao/src')
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/Account.java86
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java88
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java182
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java171
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericSearchDAO.java132
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IBasicDAO.java65
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ICatalogDAO.java72
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IElementDAO.java36
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IEsHealthCheckDao.java29
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IGenericIdDAO.java66
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IGenericSearchDAO.java42
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IPropertyDAO.java28
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IResourceDAO.java57
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IUsersDAO.java37
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ResourceUploadStatus.java25
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java110
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java75
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java383
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java207
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraDao.java65
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraOperationStatus.java26
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCacheAccessor.java48
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java293
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/ITableDescription.java46
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java425
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java71
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java95
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java103
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java105
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java95
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java101
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java104
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java100
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java103
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java104
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java102
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java104
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java99
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java101
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java99
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java132
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java104
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAdminEventTableDescription.java102
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java226
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java264
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/ActionEnum.java25
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/AdditionalInformationEnum.java25
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphEdge.java94
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphElement.java58
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphElementTypeEnum.java25
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java77
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java106
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/RelationEndPoint.java100
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java264
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java214
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java305
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java50
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/MonitoringDao.java41
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jElementDAO.java112
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java99
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java242
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java169
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchFacet.java55
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchResult.java72
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FetchContext.java32
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/GetMultipleDataResult.java113
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/BatchBuilder.java83
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTemplates.java52
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTranslator.java251
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java101
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java80
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphNeighbourTable.java64
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java212
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java1004
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jEdge.java69
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java194
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jOperationStatus.java77
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/NodeRelation.java65
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/MatchFilter.java51
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveByRelationFilter.java81
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveFilter.java68
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/UpdateFilter.java56
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/HttpRestClient.java403
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfo.java110
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/QueryType.java28
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java1848
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java872
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanOperationStatus.java26
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/CollectionUtils.java125
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/Constants.java38
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/DaoUtils.java59
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ElasticSearchUtil.java48
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/Exceptions.java35
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageQuality.java40
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageResizeUtil.java142
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/JsonUtil.java209
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapEntry.java55
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java86
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/TypeMap.java63
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/UserStatusEnum.java40
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/ArtifactDataEnum.java26
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/IResourceUploader.java76
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java155
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java183
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java131
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeValueData.java145
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java182
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java128
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityTypeData.java131
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java114
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentCacheData.java153
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java114
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java147
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java92
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/DataTypeData.java106
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java106
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/EntryData.java52
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java79
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java97
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupTypeData.java130
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java172
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java91
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java145
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java149
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InterfaceData.java91
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java88
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java130
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ProductMetadataData.java77
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java149
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java158
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipInstData.java164
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java128
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java158
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementImplData.java141
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceCategoryData.java72
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java80
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceArtifactsDataCollection.java45
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceCategoryData.java47
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceMetadataData.java62
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java112
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java47
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java228
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java95
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java84
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java135
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGenericEvent.java91
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java191
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java49
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java209
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java240
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java184
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java253
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java205
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java273
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java286
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java254
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java279
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java182
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java186
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java437
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java179
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java224
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java90
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java73
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java86
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/DeleteDeployedException.java42
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/InitializationException.java32
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/ResourceDAOException.java58
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java206
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java577
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/resources/AuditingDaoTest.java463
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/resources/CassandraTest.java74
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ESUsersDAOTest.java64
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java721
-rw-r--r--catalog-dao/src/test/resources/application-context-test.xml22
-rw-r--r--catalog-dao/src/test/resources/cassandra.yaml801
-rw-r--r--catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml120
-rw-r--r--catalog-dao/src/test/resources/config/catalog-dao/ecomp-error-configuration.yaml383
-rw-r--r--catalog-dao/src/test/resources/elasticsearch.yml392
-rw-r--r--catalog-dao/src/test/resources/images/apache.pngbin0 -> 10518 bytes
-rw-r--r--catalog-dao/src/test/resources/log4j.properties8
-rw-r--r--catalog-dao/src/test/resources/logback-test.xml13
182 files changed, 27263 insertions, 0 deletions
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/Account.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/Account.java
new file mode 100644
index 0000000000..6ff717df92
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/Account.java
@@ -0,0 +1,86 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao;
+
+//import com.datastax.driver.mapping.annotations.Column;
+//import com.datastax.driver.mapping.annotations.Frozen;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+import com.google.common.base.Objects;
+
+@Table(keyspace = "dstest", name = "accounts")
+public class Account {
+
+ @PartitionKey
+ private String email;
+ private String name;
+ // @Column (name = "addr")
+ // @Frozen
+ // private Address address;
+
+ public Account() {
+ }
+
+ // public Account(String name, String email, Address address) {
+ public Account(String name, String email) {
+ this.name = name;
+ this.email = email;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+ //
+ // public Address getAddress() {
+ // return address;
+ // }
+ //
+ // public void setAddress(Address address) {
+ // this.address = address;
+ // }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other instanceof Account) {
+ Account that = (Account) other;
+ return Objects.equal(this.name, that.name) && Objects.equal(this.email, that.email);
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(name, email);
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java
new file mode 100644
index 0000000000..9ab528ca1d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java
@@ -0,0 +1,88 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+public enum ActionStatus {
+ OK, CREATED, NO_CONTENT, GENERAL_ERROR, NOT_ALLOWED, MISSING_INFORMATION, RESTRICTED_OPERATION, RESTRICTED_ACCESS, INVALID_CONTENT,
+ // User related
+ USER_ALREADY_EXIST, USER_INACTIVE, USER_NOT_FOUND, USER_HAS_ACTIVE_ELEMENTS, INVALID_EMAIL_ADDRESS, INVALID_ROLE, DELETE_USER_ADMIN_CONFLICT, UPDATE_USER_ADMIN_CONFLICT, CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, INVALID_USER_ID,
+ // CapabilityType related
+ CAPABILITY_TYPE_ALREADY_EXIST, MISSING_CAPABILITY_TYPE, REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, IMPORT_DUPLICATE_REQ_CAP_NAME, IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED,
+ // Resource related
+ RESOURCE_NOT_FOUND, MISSING_DERIVED_FROM_TEMPLATE, PARENT_RESOURCE_NOT_FOUND, INVALID_DEFAULT_VALUE, INVALID_COMPLEX_DEFAULT_VALUE, MULTIPLE_PARENT_RESOURCE_FOUND, INVALID_RESOURCE_PAYLOAD, INVALID_TOSCA_FILE_EXTENSION, INVALID_YAML_FILE, INVALID_TOSCA_TEMPLATE, NOT_RESOURCE_TOSCA_TEMPLATE, NOT_SINGLE_RESOURCE, INVALID_RESOURCE_NAMESPACE, RESOURCE_ALREADY_EXISTS, INVALID_RESOURCE_CHECKSUM, RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, NO_ASSETS_FOUND,
+ // Component name related
+ COMPONENT_NAME_ALREADY_EXIST, COMPONENT_NAME_EXCEEDS_LIMIT, MISSING_COMPONENT_NAME, INVALID_COMPONENT_NAME,
+ // Component description related
+ COMPONENT_INVALID_DESCRIPTION, COMPONENT_MISSING_DESCRIPTION, COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
+ // Component icon related
+ COMPONENT_MISSING_ICON, COMPONENT_INVALID_ICON, COMPONENT_ICON_EXCEEDS_LIMIT,
+ // Tag related
+ COMPONENT_MISSING_TAGS, COMPONENT_TAGS_EXCEED_LIMIT, COMPONENT_SINGLE_TAG_EXCEED_LIMIT, INVALID_FIELD_FORMAT, COMPONENT_INVALID_TAGS_NO_COMP_NAME,
+ // user contact related
+ COMPONENT_MISSING_CONTACT, COMPONENT_INVALID_CONTACT,
+ // Vendor related
+ VENDOR_NAME_EXCEEDS_LIMIT, VENDOR_RELEASE_EXCEEDS_LIMIT, INVALID_VENDOR_NAME, INVALID_VENDOR_RELEASE, MISSING_VENDOR_NAME, MISSING_VENDOR_RELEASE,
+ // Category related
+ COMPONENT_MISSING_CATEGORY, COMPONENT_INVALID_CATEGORY, COMPONENT_ELEMENT_INVALID_NAME_FORMAT, COMPONENT_ELEMENT_INVALID_NAME_LENGTH, COMPONENT_CATEGORY_ALREADY_EXISTS, COMPONENT_CATEGORY_NOT_FOUND, COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY, COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY,
+ // Service API URL
+ INVALID_SERVICE_API_URL,
+ // Property related
+ PROPERTY_ALREADY_EXIST, PROPERTY_NAME_ALREADY_EXISTS, PROPERTY_NOT_FOUND, INVALID_PROPERTY, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_INNER_TYPE,
+ // Attribute related
+ ATTRIBUTE_ALREADY_EXIST, ATTRIBUTE_NOT_FOUND,
+ // State related
+ COMPONENT_IN_CHECKOUT_STATE, ILLEGAL_COMPONENT_STATE, COMPONENT_IN_CERT_IN_PROGRESS_STATE, COMPONENT_SENT_FOR_CERTIFICATION, COMPONENT_VERSION_ALREADY_EXIST, COMPONENT_ALREADY_CHECKED_IN, COMPONENT_CHECKOUT_BY_ANOTHER_USER, COMPONENT_IN_USE, COMPONENT_HAS_NEWER_VERSION, COMPONENT_ALREADY_CERTIFIED, COMPONENT_NOT_READY_FOR_CERTIFICATION, COMPONENT_ARTIFACT_NOT_FOUND, COMPONENT_INSTANCE_NOT_FOUND, COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, SERVICE_NOT_FOUND, SERVICE_CATEGORY_CANNOT_BE_CHANGED, SERVICE_NAME_CANNOT_BE_CHANGED, SERVICE_ICON_CANNOT_BE_CHANGED, COMPONENT_TOO_MUCH_CATEGORIES, SERVICE_CANNOT_CONTAIN_SUBCATEGORY, RESOURCE_CATEGORY_CANNOT_BE_CHANGED, RESOURCE_NAME_CANNOT_BE_CHANGED, RESOURCE_ICON_CANNOT_BE_CHANGED, RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED, RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED, RESOURCE_TOO_MUCH_SUBCATEGORIES, SERVICE_ICON_EXCEEDS_LIMIT, RESOURCE_INSTANCE_NOT_FOUND, RESOURCE_INSTANCE_BAD_REQUEST, RESOURCE_INSTANCE_MATCH_NOT_FOUND, RESOURCE_INSTANCE_ALREADY_EXIST, RESOURCE_INSTANCE_RELATION_NOT_FOUND, COMPONENT_MISSING_SUBCATEGORY, ARTIFACT_TYPE_NOT_SUPPORTED, MISSING_ARTIFACT_TYPE, ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED, ARTIFACT_EXIST, ARTIFACT_NOT_FOUND, ARTIFACT_INVALID_MD5, MISSING_ARTIFACT_NAME, MISSING_PROJECT_CODE, INVALID_PROJECT_CODE, COMPONENT_MISSING_MANDATORY_ARTIFACTS, LIFECYCLE_TYPE_ALREADY_EXIST, SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, MISSING_LIFECYCLE_TYPE,
+ // Distribution
+ MISSING_X_ECOMP_INSTANCE_ID, MISSING_PUBLIC_KEY, MISSING_ENV_NAME, DISTRIBUTION_ENV_DOES_NOT_EXIST, MISSING_BODY, ECOMP_RESEND_WITH_BASIC_AUTHENTICATION_CREDENTIALS, ECOMP_COMPONENT_NOT_AUTHORIZED, METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT, REGISTRATION_FAILED, DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, DISTRIBUTION_ENVIRONMENT_NOT_FOUND, DISTRIBUTION_ENVIRONMENT_INVALID, DISTRIBUTION_ARTIFACT_NOT_FOUND, DISTRIBUTION_REQUESTED_NOT_FOUND, DISTRIBUTION_REQUESTED_FAILED, DISTRIBUTION_NOT_FOUND, ADDITIONAL_INFORMATION_ALREADY_EXISTS, COMPONENT_VERSION_NOT_FOUND, ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, ADDITIONAL_INFORMATION_NOT_FOUND, SDC_VERSION_NOT_FOUND, MISSING_DATA, EXCEEDS_LIMIT, UNSUPPORTED_ERROR, ARTIFACT_INVALID_TIMEOUT, SERVICE_IS_VNF_CANNOT_BE_CHANGED, RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, WRONG_ARTIFACT_FILE_EXTENSION, INVALID_YAML, INVALID_XML, INVALID_JSON, INVALID_DEPLOYMENT_ARTIFACT_HEAT, INVALID_HEAT_PARAMETER_TYPE, INVALID_HEAT_PARAMETER_VALUE, DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, MISSING_HEAT, MISMATCH_HEAT_VS_HEAT_ENV, CORRUPTED_FORMAT, MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, INVALID_PARAMS_IN_HEAT_ENV_FILE,
+ // auth
+ AUTH_FAILED_INVALIDE_HEADER, AUTH_FAILED, AUTH_REQUIRED, CONSUMER_ALREADY_EXISTS, INVALID_LENGTH, ECOMP_USER_NOT_FOUND, INVALID_CONTENT_PARAM, INVALID_FILTER_KEY, SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, VALIDATED_RESOURCE_NOT_FOUND, FOUND_ALREADY_VALIDATED_RESOURCE, FOUND_LIST_VALIDATED_RESOURCES,
+
+ // product
+ PRODUCT_NOT_FOUND, INVALID_GROUP_ASSOCIATION, EMPTY_PRODUCT_CONTACTS_LIST, INVALID_PRODUCT_CONTACT, MISSING_ONE_OF_COMPONENT_NAMES, COMPONENT_PARAMETER_CANNOT_BE_CHANGED,
+
+ // occurrences
+ EMPTY_OCCURRENCES_LIST, INVALID_OCCURRENCES, NOT_TOPOLOGY_TOSCA_TEMPLATE, INVALID_NODE_TEMPLATE,
+
+ // Data type related
+ DATA_TYPE_ALREADY_EXIST, DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, DATA_TYPE_DERIVED_IS_MISSING, DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, DATA_TYPE_DUPLICATE_PROPERTY, DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, DATA_TYPE_CANNOT_HAVE_PROPERTIES, DATA_TYPE_CANNOT_BE_EMPTY, DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST,
+
+ // Policy Type related
+ TARGETS_EMPTY, TARGETS_NON_VALID, POLICY_TYPE_ALREADY_EXIST,
+
+ // Group Type related
+ GROUP_MEMBER_EMPTY, GROUP_TYPE_ALREADY_EXIST,
+
+ // CSAR
+ MISSING_CSAR_UUID, CSAR_INVALID, CSAR_INVALID_FORMAT, CSAR_NOT_FOUND, YAML_NOT_FOUND_IN_CSAR, VSP_ALREADY_EXISTS, RESOURCE_LINKED_TO_DIFFERENT_VSP, RESOURCE_FROM_CSAR_NOT_FOUND, AAI_ARTIFACT_GENERATION_FAILED,
+
+ // Group
+ GROUP_ALREADY_EXIST, GROUP_TYPE_IS_INVALID, GROUP_MISSING_GROUP_TYPE, GROUP_INVALID_COMPONENT_INSTANCE, GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, GROUP_IS_MISSING, GROUP_ARTIFACT_ALREADY_ASSOCIATED, GROUP_ARTIFACT_ALREADY_DISSOCIATED, GROUP_PROPERTY_NOT_FOUND, INVALID_VF_MODULE_NAME, INVALID_VF_MODULE_NAME_MODIFICATION, INVALID_VF_MODULE_TYPE,
+
+ ARTIFACT_NOT_FOUND_IN_CSAR, ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, FAILED_RETRIVE_ARTIFACTS_TYPES, ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, ARTIFACT_NOT_VALID_IN_MASTER, ARTIFACT_NOT_VALID_ENV,
+
+ // cache
+ CONVERT_COMPONENT_ERROR, COMPONENT_NOT_FOUND,
+
+ // Inputs
+ INPUT_IS_NOT_CHILD_OF_COMPONENT
+
+ ;
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java
new file mode 100644
index 0000000000..c61956313d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java
@@ -0,0 +1,182 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElement;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.impl.Neo4jResourceDAO;
+import org.openecomp.sdc.be.dao.neo4j.BatchBuilder;
+import org.openecomp.sdc.be.dao.neo4j.GraphNeighbourTable;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jClient;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jGraphBatchBuilder;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus;
+import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import fj.data.Either;
+
+public abstract class BasicDao implements IBasicDAO {
+
+ Neo4jGraphBatchBuilder graphBatchBuilder = new Neo4jGraphBatchBuilder();
+
+ Neo4jClient neo4jClient;
+
+ private static Logger logger = LoggerFactory.getLogger(Neo4jResourceDAO.class.getName());
+
+ public <T extends GraphNode> Either<T, Neo4jOperationStatus> create(GraphNeighbourTable graphNeighbourTable,
+ Class<T> clazz, NodeTypeEnum nodeType) {
+
+ if (graphNeighbourTable != null) {
+
+ Either<BatchBuilder, Neo4jOperationStatus> bbResult = graphBatchBuilder
+ .buildBatchBuilderFromTable(graphNeighbourTable);
+
+ if (bbResult.isLeft()) {
+
+ BatchBuilder batchBuilder = bbResult.left().value();
+ // Neo4jOperationStatus neo4jOperationStatus =
+ // neo4jClient.execute(batchBuilder);
+ Either<List<List<GraphElement>>, Neo4jOperationStatus> executeResult = neo4jClient
+ .execute(batchBuilder);
+
+ if (executeResult.isRight()) {
+ return Either.right(executeResult.right().value());
+ }
+
+ T result = null;
+ List<List<GraphElement>> listOfResults = executeResult.left().value();
+ if (listOfResults != null) {
+ for (List<GraphElement> listOfElements : listOfResults) {
+ if (listOfElements != null && false == listOfElements.isEmpty()) {
+ for (GraphElement element : listOfElements) {
+ logger.debug("element {} was returned after running batch operation {}", element, batchBuilder);
+ if (element instanceof GraphNode) {
+ GraphNode neo4jNode = (GraphNode) element;
+ if (NodeTypeEnum.getByName(neo4jNode.getLabel()) == nodeType) {
+ result = clazz.cast(neo4jNode);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return Either.left(result);
+
+ } else {
+ return Either.right(bbResult.right().value());
+ }
+
+ } else {
+ logger.error("The table sent in order to create resource is empty.");
+ return Either.right(Neo4jOperationStatus.BAD_REQUEST);
+ }
+
+ }
+
+ @Override
+ public <T extends GraphNode> Either<T, Neo4jOperationStatus> getNodeData(String uniqueid, Class<T> clazz,
+ NodeTypeEnum nodeTypeEnum) {
+
+ MatchFilter filter = new MatchFilter();
+ filter.addToMatch(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueid);
+
+ return getNodeData(filter, clazz, nodeTypeEnum);
+
+ }
+
+ @Override
+ public <T extends GraphNode> Either<T, Neo4jOperationStatus> getNodeData(String keyName, String uniqueid,
+ Class<T> clazz, NodeTypeEnum nodeTypeEnum) {
+
+ MatchFilter filter = new MatchFilter();
+ filter.addToMatch(keyName, uniqueid);
+
+ return getNodeData(filter, clazz, nodeTypeEnum);
+
+ }
+
+ private <T extends GraphNode> Either<T, Neo4jOperationStatus> getNodeData(MatchFilter filter, Class<T> clazz,
+ NodeTypeEnum nodeTypeEnum) {
+
+ Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node,
+ nodeTypeEnum.getName(), filter);
+
+ if (status.isRight()) {
+ return Either.right(status.right().value());
+ } else {
+ List<GraphElement> value = status.left().value();
+ if (value == null || value.isEmpty()) {
+ return Either.right(Neo4jOperationStatus.NOT_FOUND);
+ } else {
+ return Either.left(clazz.cast(value.get(0)));
+ }
+ }
+ }
+
+ @Override
+ public <T extends GraphNode> Either<List<T>, Neo4jOperationStatus> getNodesData(
+ Map<String, Object> propertiesToMatch, Class<T> clazz, NodeTypeEnum nodeTypeEnum) {
+
+ MatchFilter filter = new MatchFilter();
+ if (propertiesToMatch != null) {
+ for (Entry<String, Object> property : propertiesToMatch.entrySet()) {
+ filter.addToMatch(property.getKey(), property.getValue());
+ }
+ }
+
+ Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node,
+ nodeTypeEnum.getName(), filter);
+
+ if (status.isRight()) {
+ return Either.right(status.right().value());
+ } else {
+ List<GraphElement> value = status.left().value();
+ if (value == null || value.isEmpty()) {
+ return Either.right(Neo4jOperationStatus.NOT_FOUND);
+ } else {
+ List<T> list = new ArrayList<T>();
+ for (GraphElement element : value) {
+ list.add(clazz.cast(element));
+ }
+ return Either.left(list);
+ }
+ }
+ }
+
+ public Neo4jClient getNeo4jClient() {
+ return neo4jClient;
+ }
+
+ public void setNeo4jClient(Neo4jClient neo4jClient) {
+ this.neo4jClient = neo4jClient;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java
new file mode 100644
index 0000000000..ae2b236de1
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java
@@ -0,0 +1,171 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.Resource;
+
+import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
+import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
+import org.elasticsearch.action.get.GetResponse;
+import org.elasticsearch.action.get.MultiGetItemResponse;
+import org.elasticsearch.action.get.MultiGetResponse;
+import org.elasticsearch.client.Client;
+import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
+import org.openecomp.sdc.be.dao.utils.Exceptions;
+import org.openecomp.sdc.exception.IndexingServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public abstract class ESGenericIdDAO implements IGenericIdDAO {
+
+ private static Logger log = LoggerFactory.getLogger(ESGenericIdDAO.class.getName());
+
+ @Resource(name = "elasticsearch-client")
+ private ElasticSearchClient esClient;
+
+ private ObjectMapper jsonMapper = new ObjectMapper();
+ private final Map<String, String> typesToIndices = new HashMap<String, String>();
+
+ public Client getClient() {
+ return this.esClient.getClient();
+ }
+
+ public ElasticSearchClient getEsClient() {
+ return esClient;
+ }
+
+ public ObjectMapper getJsonMapper() {
+ return jsonMapper;
+ }
+
+ public void setJsonMapper(ObjectMapper jsonMapper) {
+ this.jsonMapper = jsonMapper;
+ }
+
+ public void addToIndicesMap(String type, String index) {
+ typesToIndices.put(type, index);
+ }
+
+ public String getIndexForType(String type) {
+ return typesToIndices.get(type);
+ }
+
+ @Override
+ public <T> T findById(String typeName, String id, Class<T> clazz) {
+
+ String indexName = getIndexForType(typeName);
+ GetResponse response = getClient().prepareGet(indexName, typeName, id).execute().actionGet();
+
+ if (response == null || !response.isExists()) {
+ log.debug("Nothing found in index <{}>, type <{}>, for Id <{}>.", indexName, typeName, id);
+ return null;
+ }
+
+ log.debug("Found one in index <{}>, type <{}>, for Id <{}>.", indexName, typeName, id);
+
+ T ret = null;
+ try {
+ ret = (T) jsonMapper.readValue(response.getSourceAsString(), clazz);
+ } catch (IOException e) {
+ Exceptions.convertToRuntimeEx(e);
+ }
+ return ret;
+ }
+
+ @Override
+ public <T> List<T> findByIds(String typeName, Class<T> clazz, String... ids) {
+ String indexName = getIndexForType(typeName);
+ MultiGetResponse response = getClient().prepareMultiGet().add(indexName, typeName, ids).execute().actionGet();
+
+ if (response == null || response.getResponses() == null || response.getResponses().length == 0) {
+ log.debug("Nothing found in index <{}>, type <{}>, for Ids <{}>.", indexName, typeName,
+ Arrays.toString(ids));
+ return null;
+ }
+
+ List<T> result = new ArrayList<>();
+ for (MultiGetItemResponse getItemResponse : response.getResponses()) {
+ if (getItemResponse.getResponse().isExists()) {
+ T val = null;
+ try {
+ val = jsonMapper.readValue(getItemResponse.getResponse().getSourceAsString(), clazz);
+ result.add(val);
+ } catch (IOException e) {
+ Exceptions.convertToRuntimeEx(e);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ protected void saveResourceData(String typeName, Object data, String id) throws JsonProcessingException {
+ String indexName = getIndexForType(typeName);
+
+ log.debug("ESGenericIdDAO saveResourceData resource indexName: {} typeName is: {}", indexName, typeName);
+
+ String json = getJsonMapper().writeValueAsString(data);
+ log.debug("ESGenericIdDAO saveResourceData resource id is: {}", id);
+ try {
+ getClient().prepareIndex(indexName, typeName, id).setSource(json).setRefresh(true).execute().actionGet();
+ } catch (Exception e) {
+ log.error("failed to write data with id {} to elasticsearch type {}. error: {}", id, typeName,
+ e.getMessage());
+ throw e;
+ }
+ }
+
+ @Override
+ public void delete(String typeName, String id) {
+ assertIdNotNullFor(id, "delete");
+ String indexName = getIndexForType(typeName);
+ getClient().prepareDelete(indexName, typeName, id).setRefresh(true).execute().actionGet();
+ }
+
+ public void deleteIndex(String indexName) {
+ DeleteIndexResponse actionGet = getClient().admin().indices().delete(new DeleteIndexRequest(indexName))
+ .actionGet();
+ if (!actionGet.isAcknowledged()) {
+ log.error("failed to delete index {}", indexName);
+ }
+ }
+
+ private void assertIdNotNullFor(String id, String operation) {
+ if (id == null || id.trim().isEmpty()) {
+ log.error("Null or empty Id is not allowed for operation <" + operation + ">.");
+ throw new IndexingServiceException("Null or empty Id is not allowed for operation <" + operation + ">.");
+ }
+ }
+
+ public static String indexTypeFromClass(Class<?> clazz) {
+ return clazz.getSimpleName().toLowerCase();
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericSearchDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericSearchDAO.java
new file mode 100644
index 0000000000..c24325aefb
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericSearchDAO.java
@@ -0,0 +1,132 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.annotation.Resource;
+
+import org.elasticsearch.action.search.SearchRequestBuilder;
+import org.elasticsearch.action.search.SearchResponse;
+import org.elasticsearch.index.query.QueryBuilder;
+import org.elasticsearch.search.sort.SortBuilder;
+import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
+import org.openecomp.sdc.be.dao.utils.Exceptions;
+
+/**
+ * Elastic search dao that manages search operations.
+ *
+ * @author luc boutier
+ */
+public class ESGenericSearchDAO extends ESGenericIdDAO implements IGenericSearchDAO {
+
+ private static final int MAX_SEARCH_SIZE = 1000;
+
+ @Resource(name = "elasticsearch-client")
+ private ElasticSearchClient esClient;
+
+ @Override
+ public long count(String indexName, String typeName, QueryBuilder query) {
+
+ SearchRequestBuilder searchRequestBuilder = esClient.getClient().prepareSearch(indexName).setTypes(typeName)
+ .setSize(0);
+ if (query != null) {
+ searchRequestBuilder.setQuery(query);
+ }
+
+ SearchResponse response = searchRequestBuilder.execute().actionGet();
+ if (!somethingFound(response)) {
+ return 0;
+ } else {
+ return response.getHits().getTotalHits();
+ }
+ }
+
+ /**
+ * Convert a SearchResponse into a list of objects (json deserialization.)
+ *
+ * @param searchResponse
+ * The actual search response from elastic-search.
+ * @param clazz
+ * The type of objects to de-serialize.
+ * @return A list of instances that contains de-serialized data.
+ */
+ public <T> List<T> toGetListOfData(SearchResponse searchResponse, Class<T> clazz) {
+ // return null if no data has been found in elastic search.
+ if (!somethingFound(searchResponse)) {
+ return null;
+ }
+
+ List<T> result = new ArrayList<>();
+
+ for (int i = 0; i < searchResponse.getHits().getHits().length; i++) {
+ try {
+ result.add(getJsonMapper().readValue(searchResponse.getHits().getAt(i).getSourceAsString(), clazz));
+ } catch (IOException e) {
+ Exceptions.convertToRuntimeEx(e);
+ }
+ }
+
+ return result;
+ }
+
+ public <T> List<T> doCustomFind(Class<T> clazz, String indexName, String typeName, QueryBuilder query,
+ SortBuilder sortBuilder) {
+
+ List<T> result = new ArrayList<T>();
+ SearchRequestBuilder searchRequestBuilder = getClient().prepareSearch(indexName).setTypes(typeName)
+ .setSize(MAX_SEARCH_SIZE);
+ if (query != null) {
+ searchRequestBuilder.setQuery(query);
+ }
+ if (sortBuilder != null) {
+ searchRequestBuilder.addSort(sortBuilder);
+ }
+ SearchResponse response = searchRequestBuilder.execute().actionGet();
+ if (!somethingFound(response)) {
+ return null;
+ } else {
+ for (int i = 0; i < response.getHits().getHits().length; i++) {
+ String hit = response.getHits().getAt(i).sourceAsString();
+
+ T val = null;
+ try {
+ val = getJsonMapper().readValue(hit, clazz);
+ result.add(val);
+ } catch (IOException e) {
+ Exceptions.convertToRuntimeEx(e);
+ }
+ }
+ return result;
+ }
+ }
+
+ private boolean somethingFound(final SearchResponse searchResponse) {
+ if (searchResponse == null || searchResponse.getHits() == null || searchResponse.getHits().getHits() == null
+ || searchResponse.getHits().getHits().length == 0) {
+ return false;
+ }
+ return true;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IBasicDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IBasicDAO.java
new file mode 100644
index 0000000000..3a2bfb34e8
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IBasicDAO.java
@@ -0,0 +1,65 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphNeighbourTable;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import fj.data.Either;
+
+public interface IBasicDAO {
+
+ /**
+ * add the content of the graph neighbour table to the graph.
+ *
+ * @param graphNeighbourTable
+ * @param clazz
+ * - the type of the object to be returned
+ * @param nodeType
+ * - label of the node
+ * @return Neo4jNode implementation
+ */
+ public <T extends GraphNode> Either<T, Neo4jOperationStatus> create(GraphNeighbourTable graphNeighbourTable,
+ Class<T> clazz, NodeTypeEnum nodeType);
+
+ /**
+ * return the node data by unique id.
+ *
+ * @param id
+ * - unique id of the node
+ * @param clazz
+ * @param nodeType
+ * @return
+ */
+ public <T extends GraphNode> Either<T, Neo4jOperationStatus> getNodeData(String id, Class<T> clazz,
+ NodeTypeEnum nodeType);
+
+ public <T extends GraphNode> Either<T, Neo4jOperationStatus> getNodeData(String keyName, String id, Class<T> clazz,
+ NodeTypeEnum nodeType);
+
+ public <T extends GraphNode> Either<List<T>, Neo4jOperationStatus> getNodesData(
+ Map<String, Object> propertiesToMatch, Class<T> clazz, NodeTypeEnum nodeTypeEnum);
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ICatalogDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ICatalogDAO.java
new file mode 100644
index 0000000000..b59e956f9c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ICatalogDAO.java
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+import java.util.List;
+
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.be.resources.exception.ResourceDAOException;
+
+import fj.data.Either;
+
+public interface ICatalogDAO {
+
+ public static final String TOSCA_ELEMENT_INDEX = "toscaelement";
+ public static final String RESOURCES_INDEX = "resources";
+ public final static String REF_NAME_FIELD = "refName";
+ public final static String REF_VERSION_FIELD = "refVersion";
+ public final static String ARTIFACT_NAME_FIELD = "artifactName";
+
+ void addToIndicesMap(String typeName, String indexName);
+
+ /**
+ * Save an artifact in the DAO layer.
+ *
+ * @param imageData
+ */
+ void writeArtifact(ESArtifactData artifactData) throws ResourceDAOException;
+
+ /**
+ * Get an artifact as a byte array based on the artifact id.
+ *
+ * @param id
+ * The id of the artifact to read.
+ * @param id2
+ * @return The artifact as a byte array.
+ */
+ Either<ESArtifactData, ResourceUploadStatus> getArtifact(String id);
+
+ Either<List<ESArtifactData>, ResourceUploadStatus> getArtifacts(String[] ids);
+
+ /**
+ * Delete the given image.
+ *
+ * @param id
+ * Id of the image to delete.
+ */
+ void deleteArtifact(String id);
+
+ /**
+ * delete all artifacts
+ */
+ void deleteAllArtifacts();
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IElementDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IElementDAO.java
new file mode 100644
index 0000000000..f43bd2303f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IElementDAO.java
@@ -0,0 +1,36 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+import java.util.List;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElement;
+
+import fj.data.Either;
+
+public interface IElementDAO {
+
+ public Either<List<GraphElement>, ActionStatus> getAllCategories();
+
+ public Either<List<GraphElement>, ActionStatus> getAllTags();
+
+ public Either<GraphElement, ActionStatus> getCategory(String name);
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IEsHealthCheckDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IEsHealthCheckDao.java
new file mode 100644
index 0000000000..e1ab8a7ba9
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IEsHealthCheckDao.java
@@ -0,0 +1,29 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
+
+public interface IEsHealthCheckDao {
+
+ public HealthCheckStatus getClusterHealthStatus();
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IGenericIdDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IGenericIdDAO.java
new file mode 100644
index 0000000000..2bc11dfcf4
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IGenericIdDAO.java
@@ -0,0 +1,66 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+import java.util.List;
+
+/**
+ * A DAO that allows accessing data by Id or / and multiple Ids.
+ *
+ * @author Igor Ngouagna
+ */
+public interface IGenericIdDAO {
+
+ /**
+ * Find an instance from the given class.
+ *
+ * @param clazz
+ * The class of the object to find.
+ * @param id
+ * The id of the object.
+ * @return The object that has the given id or null if no object matching
+ * the request is found.
+ */
+ <T> T findById(String typeName, String id, Class<T> clazz);
+
+ /**
+ * Find instances by id
+ *
+ * @param clazz
+ * The class for which to find an instance.
+ * @param ids
+ * array of id of the data to find.
+ * @return List of Objects that has the given ids or empty list if no object
+ * matching the request is found.
+ */
+ <T> List<T> findByIds(String typeName, Class<T> clazz, String... ids);
+
+ /**
+ * Delete an instance from the given class.
+ *
+ * @param clazz
+ * The class of the object to delete.
+ * @param id
+ * The id of the object to delete.
+ */
+ void delete(String typeName, String id);
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IGenericSearchDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IGenericSearchDAO.java
new file mode 100644
index 0000000000..1e0cdace2c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IGenericSearchDAO.java
@@ -0,0 +1,42 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+import org.elasticsearch.index.query.QueryBuilder;
+
+/**
+ * A Dao that supports search and/or filter based queries.
+ *
+ * @author luc boutier
+ */
+public interface IGenericSearchDAO extends IGenericIdDAO {
+
+ /**
+ * Get the index in which a class belongs.
+ *
+ * @param clazz
+ * The class for which to get the index.
+ * @return The name of the index in which the class lies.
+ */
+ String getIndexForType(String type);
+
+ long count(String indexName, String typeName, QueryBuilder query);
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IPropertyDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IPropertyDAO.java
new file mode 100644
index 0000000000..17bded535c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IPropertyDAO.java
@@ -0,0 +1,28 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+public interface IPropertyDAO extends IBasicDAO {
+
+ // Either<PropertyData, Neo4jOperationStatus>
+ // createPropertyData(GraphNeighbourTable graphNeighbourTable);
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IResourceDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IResourceDAO.java
new file mode 100644
index 0000000000..47bbcbcb11
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IResourceDAO.java
@@ -0,0 +1,57 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.neo4j.Neo4jClient;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
+
+import fj.data.Either;
+
+public interface IResourceDAO extends IBasicDAO {
+
+ Either<ResourceMetadataData, Neo4jOperationStatus> getResourceData(String id);
+
+ // Either<ResourceData, Neo4jOperationStatus>
+ // createResourceData(GraphNeighbourTable graphNeighbourTable);
+
+ /**
+ * the method retrieves all the resources according to the supplied
+ * properties, if none or null is supplied all the resources will be
+ * returned.
+ *
+ * @param propertiesToMatch
+ * a map of properties to match.
+ * @return
+ */
+ Either<List<ResourceMetadataData>, Neo4jOperationStatus> getAllResourcesData(Map<String, Object> propertiesToMatch);
+
+ // ActionStatus updateUserData(UserData userData);
+ //
+ // ActionStatus deleteUserData(String id);
+
+ void setNeo4jClient(Neo4jClient client);
+
+ Either<Integer, Neo4jOperationStatus> getNumberOfResourcesByName(String name);
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IUsersDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IUsersDAO.java
new file mode 100644
index 0000000000..441e8a9010
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IUsersDAO.java
@@ -0,0 +1,37 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+import org.openecomp.sdc.be.resources.data.UserData;
+
+import fj.data.Either;
+
+public interface IUsersDAO {
+
+ Either<UserData, ActionStatus> getUserData(String id);
+
+ ActionStatus saveUserData(UserData userData);
+
+ ActionStatus updateUserData(UserData userData);
+
+ ActionStatus deleteUserData(String id);
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ResourceUploadStatus.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ResourceUploadStatus.java
new file mode 100644
index 0000000000..88ef319657
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ResourceUploadStatus.java
@@ -0,0 +1,25 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.api;
+
+public enum ResourceUploadStatus {
+ OK, ALREADY_EXIST, NOT_EXIST, ERROR, COMPONENT_NOT_EXIST, SERVICE_NOT_EXIST
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java
new file mode 100644
index 0000000000..36d9b60eb5
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java
@@ -0,0 +1,110 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra;
+
+import javax.annotation.PostConstruct;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import com.datastax.driver.core.Session;
+import com.datastax.driver.mapping.MappingManager;
+
+import fj.data.Either;
+
+@Component("artifact-cassandra-dao")
+public class ArtifactCassandraDao extends CassandraDao {
+
+ private static Logger logger = LoggerFactory.getLogger(ArtifactCassandraDao.class.getName());
+
+ public ArtifactCassandraDao() {
+ super();
+
+ }
+
+ @PostConstruct
+ public void init() {
+ String keyspace = AuditingTypesConstants.ARTIFACT_KEYSPACE;
+ if (client.isConnected()) {
+ Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> result = client.connect(keyspace);
+ if (result.isLeft()) {
+ session = result.left().value().left;
+ manager = result.left().value().right;
+ logger.info("** ArtifactCassandraDao created");
+ } else {
+ logger.info("** ArtifactCassandraDao failed");
+ throw new RuntimeException("Artifact keyspace [" + keyspace + "] failed to connect with error : "
+ + result.right().value());
+ }
+ } else {
+ logger.info("** Cassandra client isn't connected");
+ logger.info("** ArtifactCassandraDao created, but not connected");
+ }
+ }
+
+ public CassandraOperationStatus saveArtifact(ESArtifactData artifact) {
+ return client.save(artifact, ESArtifactData.class, manager);
+ }
+
+ public Either<ESArtifactData, CassandraOperationStatus> getArtifact(String artifactId) {
+ return client.getById(artifactId, ESArtifactData.class, manager);
+ }
+
+ public CassandraOperationStatus deleteArtifact(String artifactId) {
+ return client.delete(artifactId, ESArtifactData.class, manager);
+ }
+
+ /**
+ * ---------for use in JUnit only--------------- the method deletes all the
+ * tables in the audit keyspace
+ *
+ * @return the status of the last failed operation or ok if all the deletes
+ * were successful
+ */
+ public CassandraOperationStatus deleteAllArtifacts() {
+ logger.info("cleaning all artifacts.");
+ String query = "truncate sdcArtifact.resources;";
+ try {
+ session.execute(query);
+ } catch (Exception e) {
+ logger.debug("Failed to clean artifacts", e);
+ return CassandraOperationStatus.GENERAL_ERROR;
+ }
+ logger.info("cleaning all artifacts finished succsesfully.");
+ return CassandraOperationStatus.OK;
+ }
+
+ /**
+ * the method checks if the given table is empty in the artifact keyspace
+ *
+ * @param tableName
+ * the name of the table we want to check
+ * @return true if the table is empty
+ */
+ public Either<Boolean, CassandraOperationStatus> isTableEmpty(String tableName) {
+ return super.isTableEmpty(tableName);
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java
new file mode 100644
index 0000000000..c9262909bf
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java
@@ -0,0 +1,75 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra;
+
+import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent;
+import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
+
+import com.datastax.driver.mapping.Result;
+import com.datastax.driver.mapping.annotations.Accessor;
+import com.datastax.driver.mapping.annotations.Param;
+import com.datastax.driver.mapping.annotations.Query;
+
+@Accessor
+public interface AuditAccessor {
+
+ // ***** distributionstatusevent table
+ @Query("SELECT * FROM sdcAudit.distributionstatusevent WHERE DID = :did AND ACTION = 'DStatus' ALLOW FILTERING")
+ Result<DistributionStatusEvent> getListOfDistributionStatuses(@Param("did") String did);
+
+ // ***** resourceadminevent table
+ @Query("SELECT * FROM sdcAudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'DRequest' ALLOW FILTERING")
+ Result<ResourceAdminEvent> getServiceDistributionStatus(@Param("serviceInstanceId") String serviceInstanceId);
+
+ @Query("SELECT * FROM sdcAudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId ")
+ Result<ResourceAdminEvent> getByServiceInstanceId(@Param("serviceInstanceId") String serviceInstanceId);
+
+ @Query("SELECT * FROM sdcAudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND PREV_VERSION = :prevVersion ALLOW FILTERING")
+ Result<ResourceAdminEvent> getAuditByServiceIdAndPrevVersion(@Param("serviceInstanceId") String serviceInstanceId,
+ @Param("prevVersion") String prevVersion);
+
+ @Query("SELECT * FROM sdcAudit.resourceadminevent WHERE DID = :did AND ACTION = :action ALLOW FILTERING")
+ Result<ResourceAdminEvent> getDistributionRequest(@Param("did") String did, @Param("action") String action);
+
+ @Query("SELECT * FROM sdcAudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND CURR_VERSION = :currVersion ALLOW FILTERING")
+ Result<ResourceAdminEvent> getAuditByServiceIdAndCurrVersion(@Param("serviceInstanceId") String serviceInstanceId,
+ @Param("currVersion") String currVersion);
+
+ // ***** distributiondeployevent table
+ @Query("SELECT * FROM sdcAudit.distributiondeployevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'DResult' ALLOW FILTERING")
+ Result<DistributionDeployEvent> getServiceDistributionDeploy(@Param("serviceInstanceId") String serviceInstanceId);
+
+ @Query("SELECT * FROM sdcAudit.distributiondeployevent WHERE DID = :did AND ACTION = :action AND STATUS = :status ALLOW FILTERING")
+ Result<DistributionDeployEvent> getDistributionDeployByStatus(@Param("did") String did,
+ @Param("action") String action, @Param("status") String status);
+
+ // ***** distributionnotificationevent table
+ @Query("SELECT * FROM sdcAudit.distributionnotificationevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'DNotify' ALLOW FILTERING")
+ Result<DistributionNotificationEvent> getServiceDistributionNotify(
+ @Param("serviceInstanceId") String serviceInstanceId);
+
+ @Query("SELECT * FROM sdcAudit.distributionnotificationevent WHERE DID = :did AND ACTION = :action ALLOW FILTERING")
+ Result<DistributionNotificationEvent> getDistributionNotify(@Param("did") String did,
+ @Param("action") String action);
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java
new file mode 100644
index 0000000000..73b55b909c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java
@@ -0,0 +1,383 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.annotation.PostConstruct;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.schema.Table;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent;
+import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
+import org.openecomp.sdc.common.config.EcompErrorName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import com.datastax.driver.core.Session;
+import com.datastax.driver.mapping.MappingManager;
+import com.datastax.driver.mapping.Result;
+
+import fj.data.Either;
+
+@Component("audit-cassandra-dao")
+public class AuditCassandraDao extends CassandraDao {
+
+ private AuditAccessor auditAccessor;
+
+ private static Logger logger = LoggerFactory.getLogger(AuditCassandraDao.class.getName());
+
+ public AuditCassandraDao() {
+ super();
+ }
+
+ @PostConstruct
+ public void init() {
+ String keyspace = AuditingTypesConstants.AUDIT_KEYSPACE;
+ if (client.isConnected()) {
+ Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> result = client.connect(keyspace);
+ if (result.isLeft()) {
+ session = result.left().value().left;
+ manager = result.left().value().right;
+ auditAccessor = manager.createAccessor(AuditAccessor.class);
+ logger.info("** AuditCassandraDao created");
+ } else {
+ logger.info("** AuditCassandraDao failed");
+ throw new RuntimeException(
+ "Audit keyspace [" + keyspace + "] failed to connect with error : " + result.right().value());
+ }
+ } else {
+ logger.info("** Cassandra client isn't connected");
+ logger.info("** AuditCassandraDao created, but not connected");
+ }
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T extends AuditingGenericEvent> CassandraOperationStatus saveRecord(T entity) {
+ return client.save(entity, (Class<T>) entity.getClass(), manager);
+ }
+
+ /**
+ *
+ * @param did
+ * @return
+ */
+ public Either<List<DistributionStatusEvent>, ActionStatus> getListOfDistributionStatuses(String did) {
+ List<DistributionStatusEvent> remainingElements = new ArrayList<DistributionStatusEvent>();
+
+ try {
+ Result<DistributionStatusEvent> events = auditAccessor.getListOfDistributionStatuses(did);
+ if (events == null) {
+ logger.debug("not found distribution statuses for did {}", did);
+ return Either.left(remainingElements);
+ }
+ events.all().forEach(event -> {
+ event.fillFields();
+ remainingElements.add(event);
+ logger.debug(event.toString());
+ });
+ return Either.left(remainingElements);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Get DistributionStatuses List");
+
+ logger.debug("failed to get distribution statuses for ", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ public Either<List<DistributionDeployEvent>, ActionStatus> getDistributionDeployByStatus(String did, String action,
+ String status) {
+ List<DistributionDeployEvent> remainingElements = new ArrayList<DistributionDeployEvent>();
+
+ try {
+ Result<DistributionDeployEvent> events = auditAccessor.getDistributionDeployByStatus(did, action, status);
+ if (events == null) {
+ logger.debug("not found distribution statuses for did {}", did);
+ return Either.left(remainingElements);
+ }
+ events.all().forEach(event -> {
+ event.fillFields();
+ remainingElements.add(event);
+ logger.debug(event.toString());
+ });
+
+ return Either.left(remainingElements);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution Deploy By Status");
+
+ logger.debug("failed to get distribution deploy by status for ", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ public Either<List<ResourceAdminEvent>, ActionStatus> getDistributionRequest(String did, String action) {
+ List<ResourceAdminEvent> remainingElements = new ArrayList<ResourceAdminEvent>();
+
+ try {
+ Result<ResourceAdminEvent> events = auditAccessor.getDistributionRequest(did, action);
+ if (events == null) {
+ logger.debug("not found distribution requests for did {}", did);
+ return Either.left(remainingElements);
+ }
+ events.all().forEach(event -> {
+ event.fillFields();
+ remainingElements.add(event);
+ logger.debug(event.toString());
+ });
+ return Either.left(remainingElements);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution request");
+
+ logger.debug("failed to get distribution request for ", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ public Either<List<DistributionNotificationEvent>, ActionStatus> getDistributionNotify(String did, String action) {
+ List<DistributionNotificationEvent> remainingElements = new ArrayList<DistributionNotificationEvent>();
+
+ try {
+ Result<DistributionNotificationEvent> events = auditAccessor.getDistributionNotify(did, action);
+ if (events == null) {
+ logger.debug("not found distribution notify for did {}", did);
+ return Either.left(remainingElements);
+ }
+ events.all().forEach(event -> {
+ event.fillFields();
+ remainingElements.add(event);
+ logger.debug(event.toString());
+ });
+
+ return Either.left(remainingElements);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution notify");
+
+ logger.debug("failed to get distribution notify for ", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ public Either<List<ResourceAdminEvent>, ActionStatus> getByServiceInstanceId(String serviceInstanceId) {
+ List<ResourceAdminEvent> remainingElements = new ArrayList<ResourceAdminEvent>();
+
+ try {
+ Result<ResourceAdminEvent> events = auditAccessor.getByServiceInstanceId(serviceInstanceId);
+ if (events == null) {
+ logger.debug("not found audit records for serviceInstanceId {}", serviceInstanceId);
+ return Either.left(remainingElements);
+ }
+ events.all().forEach(event -> {
+ event.fillFields();
+ remainingElements.add(event);
+ logger.debug(event.toString());
+ });
+ return Either.left(remainingElements);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution notify");
+
+ logger.debug("failed to get distribution notify for ", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ /**
+ *
+ * @param serviceInstanceId
+ * @return
+ */
+ public Either<List<? extends AuditingGenericEvent>, ActionStatus> getServiceDistributionStatusesList(
+ String serviceInstanceId) {
+
+ List<AuditingGenericEvent> resList = new ArrayList<>();
+
+ try {
+ Result<ResourceAdminEvent> resourceAdminEvents = auditAccessor
+ .getServiceDistributionStatus(serviceInstanceId);
+
+ if (resourceAdminEvents != null) {
+ resourceAdminEvents.all().forEach(event -> {
+ event.fillFields();
+ resList.add(event);
+ logger.debug(event.toString());
+ });
+ }
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get Service DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
+ logger.debug("failed to get distribution statuses for action {}",
+ AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ try {
+ Result<DistributionDeployEvent> distDeployEvents = auditAccessor
+ .getServiceDistributionDeploy(serviceInstanceId);
+ if (distDeployEvents != null) {
+ distDeployEvents.all().forEach(event -> {
+ event.fillFields();
+ resList.add(event);
+ logger.debug(event.toString());
+ });
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get Service DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
+ logger.debug("failed to get distribution statuses for action {}",
+ AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ try {
+ Result<DistributionNotificationEvent> distNotifEvent = auditAccessor
+ .getServiceDistributionNotify(serviceInstanceId);
+ if (distNotifEvent != null) {
+ distNotifEvent.all().forEach(event -> {
+ event.fillFields();
+ resList.add(event);
+ logger.debug(event.toString());
+ });
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get Service DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
+ logger.debug("failed to get distribution statuses for action {}",
+ AuditingActionEnum.DISTRIBUTION_NOTIFY.getName(), e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+
+ return Either.left(resList);
+ }
+
+ public Either<List<ResourceAdminEvent>, ActionStatus> getAuditByServiceIdAndPrevVersion(String serviceInstanceId,
+ String prevVersion) {
+ List<ResourceAdminEvent> remainingElements = new ArrayList<ResourceAdminEvent>();
+
+ try {
+ Result<ResourceAdminEvent> events = auditAccessor.getAuditByServiceIdAndPrevVersion(serviceInstanceId,
+ prevVersion);
+ if (events == null) {
+ logger.debug("not found audit records for serviceInstanceId {} andprevVersion {}", serviceInstanceId,
+ prevVersion);
+ return Either.left(remainingElements);
+ }
+ events.all().forEach(event -> {
+ event.fillFields();
+ remainingElements.add(event);
+ logger.debug(event.toString());
+ });
+ return Either.left(remainingElements);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "get Audit By ServiceId And PrevVersion");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("get Audit By ServiceId And PrevVersion");
+
+ logger.debug("failed to getAuditByServiceIdAndPrevVersion ", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ public Either<List<ResourceAdminEvent>, ActionStatus> getAuditByServiceIdAndCurrVersion(String serviceInstanceId,
+ String currVersion) {
+ List<ResourceAdminEvent> remainingElements = new ArrayList<ResourceAdminEvent>();
+
+ try {
+ Result<ResourceAdminEvent> events = auditAccessor.getAuditByServiceIdAndCurrVersion(serviceInstanceId,
+ currVersion);
+ if (events == null) {
+ logger.debug("not found audit records for serviceInstanceId {} andprevVersion {}", serviceInstanceId,
+ currVersion);
+ return Either.left(remainingElements);
+ }
+ events.all().forEach(event -> {
+ event.fillFields();
+ remainingElements.add(event);
+ logger.debug(event.toString());
+ });
+ return Either.left(remainingElements);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "get Audit By ServiceId And CurrVersion");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("get Audit By ServiceId And CurrVersion");
+
+ logger.debug("failed to getAuditByServiceIdAndPrevVersion ", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ /**
+ * the method checks if the given table is empty in the audit keyspace
+ *
+ * @param tableName
+ * the name of the table we want to check
+ * @return true if the table is empty
+ */
+ public Either<Boolean, CassandraOperationStatus> isTableEmpty(String tableName) {
+ return super.isTableEmpty(tableName);
+ }
+
+ /**
+ * ---------for use in JUnit only--------------- the method deletes all the
+ * tables in the audit keyspace
+ *
+ * @return the status of the last failed operation or ok if all the deletes
+ * were successful
+ */
+ public CassandraOperationStatus deleteAllAudit() {
+ logger.info("cleaning all audit tables.");
+ String query = "truncate " + AuditingTypesConstants.AUDIT_KEYSPACE + ".";
+ try {
+ for (Table table : Table.values()) {
+ if (table.getTableDescription().getKeyspace().equals(AuditingTypesConstants.AUDIT_KEYSPACE)) {
+ logger.debug("clean Audit table:{}", table.getTableDescription().getTableName());
+ session.execute(query + table.getTableDescription().getTableName() + ";");
+ logger.debug("clean Audit table:{} was succsesfull", table.getTableDescription().getTableName());
+ }
+ }
+ } catch (Exception e) {
+ logger.error("Failed to clean Audit", e);
+ return CassandraOperationStatus.GENERAL_ERROR;
+ }
+ logger.info("clean all audit finished succsesfully.");
+ return CassandraOperationStatus.OK;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java
new file mode 100644
index 0000000000..10b9b0578c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java
@@ -0,0 +1,207 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra;
+
+import java.util.List;
+
+import javax.annotation.PreDestroy;
+
+import com.datastax.driver.core.policies.*;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.mapping.Mapper;
+import com.datastax.driver.mapping.MappingManager;
+
+import fj.data.Either;
+
+@Component("cassandra-client")
+public class CassandraClient {
+ private static Logger logger = LoggerFactory.getLogger(CassandraClient.class.getName());
+
+ private Cluster cluster;
+ private boolean isConnected;
+
+ public CassandraClient() {
+ super();
+ isConnected = false;
+ List<String> cassandraHosts = null;
+ try {
+ cassandraHosts = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
+ .getCassandraHosts();
+ Long reconnectTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getCassandraConfig().getReconnectTimeout();
+
+ logger.debug("creating cluster to hosts:{} with reconnect timeout:{}", cassandraHosts, reconnectTimeout);
+ Cluster.Builder clusterBuilder = Cluster.builder()
+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout))
+ .withRetryPolicy(DefaultRetryPolicy.INSTANCE);
+
+ cassandraHosts.forEach(host -> clusterBuilder.addContactPoint(host));
+ enableAuthentication(clusterBuilder);
+ enableSsl(clusterBuilder);
+ setLocalDc(clusterBuilder);
+
+ cluster = clusterBuilder.build();
+ isConnected = true;
+ } catch (Exception e) {
+ logger.info("** CassandraClient isn't connected to {}", cassandraHosts);
+ }
+
+ logger.info("** CassandraClient created");
+ }
+
+ private void setLocalDc(Cluster.Builder clusterBuilder) {
+ String localDataCenter = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
+ .getLocalDataCenter();
+ if (localDataCenter != null) {
+ logger.info("localDatacenter was provided, setting Cassndra clint to use datacenter: {} as local.",
+ localDataCenter);
+ LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
+ DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
+ clusterBuilder.withLoadBalancingPolicy(tokenAwarePolicy);
+ } else {
+ logger.info(
+ "localDatacenter was provided, the driver will use the datacenter of the first contact point that was reached at initialization");
+ }
+ }
+
+ private void enableSsl(Cluster.Builder clusterBuilder) {
+ boolean ssl = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().isSsl();
+ if (ssl) {
+ String truststorePath = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getCassandraConfig().getTruststorePath();
+ String truststorePassword = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getCassandraConfig().getTruststorePassword();
+ if (truststorePath == null || truststorePassword == null) {
+ logger.error("ssl is enabled but truststorePath or truststorePassword were not supplied.");
+ } else {
+ System.setProperty("javax.net.ssl.trustStore", truststorePath);
+ System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
+ clusterBuilder.withSSL();
+ }
+
+ }
+ }
+
+ private void enableAuthentication(Cluster.Builder clusterBuilder) {
+ boolean authenticate = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
+ .isAuthenticate();
+ if (authenticate) {
+ String username = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
+ .getUsername();
+ String password = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
+ .getPassword();
+ if (username == null || password == null) {
+ logger.error("authentication is enabled but username or password were not supplied.");
+ } else {
+ clusterBuilder.withCredentials(username, password);
+ }
+
+ }
+ }
+
+ /**
+ *
+ * @param keyspace
+ * - key space to connect
+ * @return
+ */
+ public Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> connect(String keyspace) {
+ if (cluster != null) {
+ try {
+ Session session = cluster.connect(keyspace);
+ if (session != null) {
+ MappingManager manager = new MappingManager(session);
+ return Either.left(new ImmutablePair<Session, MappingManager>(session, manager));
+ } else {
+ return Either.right(CassandraOperationStatus.KEYSPACE_NOT_CONNECTED);
+ }
+ } catch (Throwable e) {
+ logger.debug("Failed to connect to keyspace [{}], error :", keyspace, e);
+ return Either.right(CassandraOperationStatus.KEYSPACE_NOT_CONNECTED);
+ }
+ }
+ return Either.right(CassandraOperationStatus.CLUSTER_NOT_CONNECTED);
+ }
+
+ public <T> CassandraOperationStatus save(T entity, Class<T> clazz, MappingManager manager) {
+ if (!isConnected) {
+ return CassandraOperationStatus.CLUSTER_NOT_CONNECTED;
+ }
+ try {
+ Mapper<T> mapper = manager.mapper(clazz);
+ mapper.save(entity);
+ } catch (Exception e) {
+ logger.debug("Failed to save entity [{}], error :", entity, e);
+ return CassandraOperationStatus.GENERAL_ERROR;
+ }
+ return CassandraOperationStatus.OK;
+ }
+
+ public <T> Either<T, CassandraOperationStatus> getById(String id, Class<T> clazz, MappingManager manager) {
+ if (!isConnected) {
+ return Either.right(CassandraOperationStatus.CLUSTER_NOT_CONNECTED);
+ }
+ try {
+ Mapper<T> mapper = manager.mapper(clazz);
+ T result = mapper.get(id);
+ if (result == null) {
+ return Either.right(CassandraOperationStatus.NOT_FOUND);
+ }
+ return Either.left(result);
+ } catch (Exception e) {
+ logger.debug("Failed to get by Id [{}], error :", id, e);
+ return Either.right(CassandraOperationStatus.GENERAL_ERROR);
+ }
+ }
+
+ public <T> CassandraOperationStatus delete(String id, Class<T> clazz, MappingManager manager) {
+ if (!isConnected) {
+ return CassandraOperationStatus.CLUSTER_NOT_CONNECTED;
+ }
+ try {
+ Mapper<T> mapper = manager.mapper(clazz);
+ mapper.delete(id);
+ } catch (Exception e) {
+ logger.debug("Failed to delete by id [{}], error :", id, e);
+ return CassandraOperationStatus.GENERAL_ERROR;
+ }
+ return CassandraOperationStatus.OK;
+ }
+
+ public boolean isConnected() {
+ return isConnected;
+ }
+
+ @PreDestroy
+ public void closeClient() {
+ if (isConnected) {
+ cluster.close();
+ }
+ logger.info("** CassandraClient cluster closed");
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraDao.java
new file mode 100644
index 0000000000..1d2eb15354
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraDao.java
@@ -0,0 +1,65 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra;
+
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Statement;
+import com.datastax.driver.core.querybuilder.QueryBuilder;
+import fj.data.Either;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.datastax.driver.core.Session;
+import com.datastax.driver.mapping.MappingManager;
+
+public abstract class CassandraDao {
+
+ private static Logger logger = LoggerFactory.getLogger(CassandraDao.class.getName());
+
+ protected Session session;
+ protected MappingManager manager;
+
+ @Autowired
+ protected CassandraClient client;
+
+ /**
+ * the method checks if the given table is empty under the keyspace the
+ * session was opened to.
+ *
+ * @param tableName
+ * the name of the table we want to check
+ * @return returns true if the table was empty
+ */
+ protected Either<Boolean, CassandraOperationStatus> isTableEmpty(String tableName) {
+
+ Statement select = QueryBuilder.select().countAll().from(tableName).limit(10);
+ try {
+ ResultSet res = session.execute(select);
+ return Either.left((res.one().getLong("count") != 0 ? false : true));
+
+ } catch (Exception e) {
+ logger.debug("Failed check if table is empty", e);
+ return Either.right(CassandraOperationStatus.GENERAL_ERROR);
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraOperationStatus.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraOperationStatus.java
new file mode 100644
index 0000000000..52b71c780b
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraOperationStatus.java
@@ -0,0 +1,26 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra;
+
+public enum CassandraOperationStatus {
+ OK, CLUSTER_NOT_CONNECTED, KEYSPACE_NOT_CONNECTED, GENERAL_ERROR, NOT_FOUND
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCacheAccessor.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCacheAccessor.java
new file mode 100644
index 0000000000..828072a4e6
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCacheAccessor.java
@@ -0,0 +1,48 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra;
+
+import java.util.List;
+
+import org.openecomp.sdc.be.resources.data.ComponentCacheData;
+
+import com.datastax.driver.mapping.Result;
+import com.datastax.driver.mapping.annotations.Accessor;
+import com.datastax.driver.mapping.annotations.Param;
+import com.datastax.driver.mapping.annotations.Query;
+
+@Accessor
+public interface ComponentCacheAccessor {
+
+ @Query("SELECT * FROM sdccomponent.componentcache WHERE id IN :ids ALLOW FILTERING")
+ Result<ComponentCacheData> getComponents(@Param("ids") List<String> ids);
+
+ @Query("SELECT * FROM sdccomponent.componentcache WHERE id = :id ALLOW FILTERING")
+ Result<ComponentCacheData> getComponent(@Param("id") String id);
+
+ @Query("SELECT id,modification_time,type FROM sdccomponent.componentcache ALLOW FILTERING")
+ Result<ComponentCacheData> getAllComponentIdTimeAndType();
+
+ // @Query("SELECT * FROM sdcartifact.resources LIMIT 2000")
+ // Result<ESArtifactData> getListOfResources();
+
+ // Result<ESArtifactData> getListOfResources(List<String> dids);
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java
new file mode 100644
index 0000000000..546dff855e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java
@@ -0,0 +1,293 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import javax.annotation.PostConstruct;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.resources.data.ComponentCacheData;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import com.datastax.driver.core.Session;
+import com.datastax.driver.mapping.MappingManager;
+import com.datastax.driver.mapping.Result;
+
+import fj.data.Either;
+
+@Component("component-cassandra-dao")
+public class ComponentCassandraDao extends CassandraDao {
+
+ private static Logger logger = LoggerFactory.getLogger(ComponentCassandraDao.class.getName());
+
+ public static Integer DEFAULT_FETCH_SIZE = 500;
+
+ private ComponentCacheAccessor componentCacheAccessor;
+
+ public ComponentCassandraDao() {
+ super();
+
+ }
+
+ @PostConstruct
+ public void init() {
+ String keyspace = AuditingTypesConstants.COMPONENT_KEYSPACE;
+ if (client.isConnected()) {
+ Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> result = client.connect(keyspace);
+ if (result.isLeft()) {
+ session = result.left().value().left;
+ manager = result.left().value().right;
+ componentCacheAccessor = manager.createAccessor(ComponentCacheAccessor.class);
+ logger.info("** ComponentCassandraDao created");
+ } else {
+ logger.info("** ComponentCassandraDao failed");
+ throw new RuntimeException("Artifact keyspace [" + keyspace + "] failed to connect with error : "
+ + result.right().value());
+ }
+ } else {
+ logger.info("** Cassandra client isn't connected");
+ logger.info("** ComponentCassandraDao created, but not connected");
+ }
+ }
+
+ /**
+ *
+ * @param ids
+ * - list of components unique id
+ * @return
+ */
+ public Either<List<ComponentCacheData>, ActionStatus> getComponents(List<String> ids) {
+
+ List<ComponentCacheData> components = new ArrayList<ComponentCacheData>();
+ if (ids == null || true == ids.isEmpty()) {
+ return Either.left(components);
+ }
+
+ try {
+
+ Result<ComponentCacheData> events = componentCacheAccessor.getComponents(ids);
+ if (events == null) {
+ logger.trace("not found component for ids list of in size {}", ids.size());
+ return Either.left(components);
+ }
+ events.all().forEach(event -> {
+ components.add(event);
+ if (logger.isTraceEnabled()) {
+ logger.trace("Fetch component uid = {} isDirty = {}", event.getId(), event.getIsDirty());
+ }
+ });
+
+ logger.debug("Number of components to fetch was {}. Actually, {} components fetched", ids.size(),
+ components.size());
+
+ return Either.left(components);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("GetComponentsFromCache");
+
+ logger.debug("failed to get components from cache", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ public Either<List<ComponentCacheData>, ActionStatus> getAllComponentIdTimeAndType() {
+ try {
+ List<ComponentCacheData> components = new ArrayList<ComponentCacheData>();
+ Result<ComponentCacheData> events = componentCacheAccessor.getAllComponentIdTimeAndType();
+ if (events == null) {
+ logger.trace("no component found ");
+ return Either.left(components);
+ }
+ events.all().forEach(event -> {
+ components.add(event);
+ if (logger.isTraceEnabled()) {
+ logger.trace("Fetch component uid = {} isDirty = {}", event.getId(), event.getIsDirty());
+ }
+ });
+
+ logger.debug("Number of components fetched was {}.", components.size());
+
+ return Either.left(components);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("GetComponentsFromCache");
+
+ logger.debug("failed to get components from cache", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ /**
+ *
+ * @param id
+ * - component unique id
+ * @return
+ */
+ public Either<ComponentCacheData, ActionStatus> getComponent(String id) {
+
+ if (id == null) {
+ return Either.right(ActionStatus.INVALID_CONTENT);
+ }
+
+ try {
+
+ Result<ComponentCacheData> events = componentCacheAccessor.getComponent(id);
+ if (events == null) {
+ logger.trace("not found component for id {}", id);
+ return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+
+ ComponentCacheData componentCacheData = events.one();
+ if (componentCacheData != null) {
+ logger.debug("Component with id {} was found. isDirty={}.", componentCacheData.getId(),
+ componentCacheData.getIsDirty());
+ } else {
+ return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+ return Either.left(componentCacheData);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("GetComponentFromCache");
+
+ logger.trace("Failed to get component from cache", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ public CassandraOperationStatus saveComponent(ComponentCacheData componentCacheData) {
+ return client.save(componentCacheData, ComponentCacheData.class, manager);
+ }
+
+ /**
+ * ---------for use in JUnit only--------------- the method deletes all the
+ * tables in the audit keyspace
+ *
+ * @return the status of the last failed operation or ok if all the deletes
+ * were successful
+ */
+ // public CassandraOperationStatus
+ // deleteAllPartialComponents(ComponentTypeEnum componentTypeEnum) {
+ // logger.info("cleaning all partial components of " + componentTypeEnum);
+ //
+ // String tableName = getTableName(componentTypeEnum);
+ // if (tableName == null) {
+ // BeEcompErrorManager.getInstance().logInvalidInputError("DeletePartialComponentData",
+ // "input type not found " + componentTypeEnum, ErrorSeverity.INFO);
+ // return CassandraOperationStatus.NOT_FOUND;
+ // }
+ // String query = "truncate " + AuditingTypesConstants.COMPONENT_KEYSPACE +
+ // "." + tableName;
+ // try {
+ // session.execute(query);
+ // } catch (Exception e) {
+ // logger.debug("Failed to clean partial components", e);
+ // return CassandraOperationStatus.GENERAL_ERROR;
+ // }
+ // logger.info("cleaning all partial components finished succsesfully.");
+ // return CassandraOperationStatus.OK;
+ // }
+
+ /**
+ * the method checks if the given table is empty in the artifact keyspace
+ *
+ * @param tableName
+ * the name of the table we want to check
+ * @return true if the table is empty
+ */
+ public Either<Boolean, CassandraOperationStatus> isTableEmpty(String tableName) {
+ return super.isTableEmpty(tableName);
+ }
+
+ /**
+ *
+ * @param idToTimestampMap
+ * - list of components unique id
+ * @return
+ */
+ public Either<ImmutablePair<List<ComponentCacheData>, Set<String>>, ActionStatus> getComponents(
+ Map<String, Long> idToTimestampMap) {
+
+ List<ComponentCacheData> components = new ArrayList<ComponentCacheData>();
+ Set<String> notFetchedFromCache = new HashSet<>();
+ ImmutablePair<List<ComponentCacheData>, Set<String>> result = new ImmutablePair<List<ComponentCacheData>, Set<String>>(
+ components, notFetchedFromCache);
+
+ if (idToTimestampMap == null || true == idToTimestampMap.isEmpty()) {
+ return Either.left(result);
+ }
+
+ try {
+
+ Set<String> keySet = idToTimestampMap.keySet();
+ List<String> ids = new ArrayList<>();
+ ids.addAll(keySet);
+ Result<ComponentCacheData> events = componentCacheAccessor.getComponents(ids);
+ if (events == null) {
+ logger.trace("not found component for ids list of in size {}", ids.size());
+ notFetchedFromCache.addAll(idToTimestampMap.keySet());
+ return Either.left(result);
+ }
+ events.all().forEach(event -> {
+ long timeFromCache = event.getModificationTime().getTime();
+ long timeRequested = idToTimestampMap.get(event.getId());
+ if (timeFromCache == timeRequested) {
+ logger.trace("Fetch component uid = {} from cache", event.getId());
+ components.add(event);
+ } else {
+ logger.trace(
+ "Fetch and ignore component uid = {} from cache. Time requested is {} while timestamp in cache is {}",
+ event.getId(), timeRequested, timeFromCache);
+ }
+ });
+
+ logger.debug("Number of components to fetch was {}. Actually, {} components fetched", ids.size(),
+ components.size());
+ List<String> foundComponents = components.stream().map(p -> p.getId()).collect(Collectors.toList());
+ // fetch all ids which was not found in cache/found in cache and not
+ // updated.
+ Set<String> notFoundComponents = idToTimestampMap.keySet().stream()
+ .filter(p -> false == foundComponents.contains(p)).collect(Collectors.toSet());
+
+ notFetchedFromCache.addAll(notFoundComponents);
+
+ return Either.left(result);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("GetComponentsFromCache");
+
+ logger.debug("failed to get components from cache", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ }
+
+ public CassandraOperationStatus deleteComponent(String id) {
+ return client.delete(id, ComponentCacheData.class, manager);
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/ITableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/ITableDescription.java
new file mode 100644
index 0000000000..010c3ee8fc
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/ITableDescription.java
@@ -0,0 +1,46 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+
+import com.datastax.driver.core.DataType;
+
+public interface ITableDescription {
+
+ public static final String TIMESTAMP_FIELD = "timestamp1";
+ public static final String TIMEBASED_UUID_FIELD = "timebaseduuid";
+ public static final String ID_FIELD = "id";
+
+ public List<ImmutablePair<String, DataType>> primaryKeys();
+
+ public List<ImmutablePair<String, DataType>> clusteringKeys();
+
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription();
+
+ public String getKeyspace();
+
+ public String getTableName();
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java
new file mode 100644
index 0000000000..0f54a25c14
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java
@@ -0,0 +1,425 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema;
+
+import com.datastax.driver.core.*;
+import com.datastax.driver.core.schemabuilder.Alter;
+import com.datastax.driver.core.schemabuilder.Create;
+import com.datastax.driver.core.schemabuilder.SchemaBuilder;
+import com.datastax.driver.core.schemabuilder.SchemaStatement;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.config.*;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLContext;
+import java.security.NoSuchAlgorithmException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class SdcSchemaBuilder {
+
+ /**
+ * creat key space statment for SimpleStrategy
+ */
+ final static String CREATE_KEYSPACE_SIMPLE_STRATEGY = "CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class':'SimpleStrategy', %s};";
+ /**
+ * creat key space statment for NetworkTopologyStrategy
+ */
+ final static String CREATE_KEYSPACE_NETWORK_TOPOLOGY_STRATEGY = "CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class':'NetworkTopologyStrategy', %s};";
+
+ private static Logger log = LoggerFactory.getLogger(SdcSchemaBuilder.class.getName());
+
+ /**
+ * the method creates all keyspaces, tables and indexes in case they do not
+ * already exist. the method can be run multiple times. the method uses the
+ * internal enums and external configuration for its operation
+ *
+ * @return true if the create operation was successful
+ */
+ public static boolean createSchema() {
+ Cluster cluster = null;
+ Session session = null;
+ try {
+ log.info("creating Schema for Cassandra.");
+ cluster = createCluster();
+ if (cluster == null) {
+ return false;
+ }
+ session = cluster.connect();
+ List<KeyspaceMetadata> keyspacesMetadateFromCassandra = cluster.getMetadata().getKeyspaces();
+ if (keyspacesMetadateFromCassandra == null) {
+ log.debug("filed to retrive a list of keyspaces from cassndra");
+ return false;
+ }
+ log.debug("retrived Cassndra metadata.");
+ Map<String, Map<String, List<String>>> cassndraMetadata = parseKeyspaceMetadata(
+ keyspacesMetadateFromCassandra);
+ Map<String, List<ITableDescription>> schemeData = getSchemeData();
+ log.info("creating Keyspaces.");
+ for (String keyspace : schemeData.keySet()) {
+ if (!createKeyspace(keyspace, cassndraMetadata, session)) {
+ return false;
+ }
+ Map<String, List<String>> keyspaceMetadate = cassndraMetadata.get(keyspace);
+ createTables(schemeData.get(keyspace), keyspaceMetadate, session);
+
+ }
+ return true;
+ } catch (Exception e) {
+ log.info("createSchema failed with exception.", e);
+ } finally {
+ if (session != null) {
+ session.close();
+ }
+ if (cluster != null) {
+ cluster.close();
+ }
+
+ }
+
+ return false;
+ }
+
+ public static boolean deleteSchema() {
+ Cluster cluster = null;
+ Session session = null;
+ try {
+ log.info("delete Data from Cassandra.");
+ cluster = createCluster();
+ if (cluster == null) {
+ return false;
+ }
+ session = cluster.connect();
+ List<KeyspaceMetadata> keyspacesMetadateFromCassandra = cluster.getMetadata().getKeyspaces();
+ if (keyspacesMetadateFromCassandra == null) {
+ log.debug("filed to retrive a list of keyspaces from cassndra");
+ return false;
+ }
+ log.debug("retrived Cassndra metadata.");
+ Map<String, Map<String, List<String>>> cassndraMetadata = parseKeyspaceMetadata(
+ keyspacesMetadateFromCassandra);
+ cassndraMetadata.forEach((k, v) -> {
+ if (AuditingTypesConstants.TITAN_KEYSPACE.equals(k)) {
+
+ // session.execute("")
+ } else if (AuditingTypesConstants.ARTIFACT_KEYSPACE.equals(k)) {
+
+ } else if (AuditingTypesConstants.AUDIT_KEYSPACE.equals(k)) {
+
+ }
+ });
+
+ System.out.println(cassndraMetadata);
+ return true;
+ } catch (Exception e) {
+ log.info("deleteSchema failed with exception.", e);
+ } finally {
+ if (session != null) {
+ session.close();
+ }
+ if (cluster != null) {
+ cluster.close();
+ }
+
+ }
+
+ return false;
+ }
+
+ /**
+ * the method creates the cluster object using the supplied cassandra nodes
+ * in the configuration
+ *
+ * @return cluster object our null in case of an invalid configuration
+ */
+ private static Cluster createCluster() {
+ List<String> nodes = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
+ .getCassandraHosts();
+ if (nodes == null) {
+ log.info("no nodes were supplied in configuration.");
+ return null;
+ }
+ log.info("connecting to node:{}.", nodes);
+ Cluster.Builder clusterBuilder = Cluster.builder();
+ nodes.forEach(host -> clusterBuilder.addContactPoint(host));
+
+ clusterBuilder.withMaxSchemaAgreementWaitSeconds(60);
+
+ boolean authenticate = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
+ .isAuthenticate();
+ if (authenticate) {
+ String username = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
+ .getUsername();
+ String password = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
+ .getPassword();
+ if (username == null || password == null) {
+ log.info("authentication is enabled but username or password were not supplied.");
+ return null;
+ }
+ clusterBuilder.withCredentials(username, password);
+ }
+ boolean ssl = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().isSsl();
+ if (ssl) {
+ String truststorePath = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getCassandraConfig().getTruststorePath();
+ String truststorePassword = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getCassandraConfig().getTruststorePassword();
+ if (truststorePath == null || truststorePassword == null) {
+ log.info("ssl is enabled but truststorePath or truststorePassword were not supplied.");
+ return null;
+ }
+ System.setProperty("javax.net.ssl.trustStore", truststorePath);
+ System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
+ clusterBuilder.withSSL();
+ }
+ return clusterBuilder.build();
+ }
+
+ /**
+ * the method prcess the metadata retrieved from the cassandra for the
+ * creation of a map conting the names of keyspaces tabls and indexes
+ * already defined in the cassandra keyspacename -> tablename -> list of
+ * indexes info
+ *
+ * @param keyspacesMetadata
+ * cassndra mmetadata
+ * @return a map of maps of lists holding parsed info
+ */
+ private static Map<String, Map<String, List<String>>> parseKeyspaceMetadata(
+ List<KeyspaceMetadata> keyspacesMetadata) {
+ Map<String, Map<String, List<String>>> cassndraMetadata = keyspacesMetadata.stream()
+ .collect(Collectors.toMap(keyspaceMetadata -> keyspaceMetadata.getName(),
+ keyspaceMetadata -> keyspaceMetadata.getTables().stream()
+ .collect(Collectors.toMap(tableMetadata -> tableMetadata.getName(),
+ tableMetadata -> tableMetadata.getIndexes().stream()
+ .map(indexMetadata -> indexMetadata.getName())
+ .collect(Collectors.toList())))));
+ return cassndraMetadata;
+ }
+
+ /**
+ * the method builds an index name according to a defined logic
+ * <table>
+ * _<column>_idx
+ *
+ * @param table
+ * table name
+ * @param column
+ * column name
+ * @return string name of the index
+ */
+ private static String createIndexName(String table, String column) {
+ return new StringBuilder().append(table).append("_").append(column).append("_idx").toString();
+ }
+
+ /**
+ * the method creats all the tables and indexes thet do not already exist
+ *
+ * @param iTableDescriptions
+ * a list of table description we want to create
+ * @param keyspaceMetadate
+ * the current tables that exist in the cassandra under this
+ * keyspace
+ * @param session
+ * the session object used for the execution of the query.
+ */
+ private static void createTables(List<ITableDescription> iTableDescriptions,
+ Map<String, List<String>> keyspaceMetadate, Session session) {
+
+ for (ITableDescription tableDescription : iTableDescriptions) {
+ String tableName = tableDescription.getTableName().toLowerCase();
+ Map<String, ImmutablePair<DataType, Boolean>> columnDescription = tableDescription.getColumnDescription();
+ log.info("creating tables:{}.", tableName);
+ if (keyspaceMetadate == null || !keyspaceMetadate.keySet().contains(tableName)) {
+ Create create = SchemaBuilder.createTable(tableDescription.getKeyspace(),
+ tableDescription.getTableName());
+ for (ImmutablePair<String, DataType> key : tableDescription.primaryKeys()) {
+ create.addPartitionKey(key.getLeft(), key.getRight());
+ }
+ if (tableDescription.clusteringKeys() != null) {
+ for (ImmutablePair<String, DataType> key : tableDescription.clusteringKeys()) {
+ create.addClusteringColumn(key.getLeft(), key.getRight());
+ }
+ }
+
+ for (String columnName : columnDescription.keySet()) {
+ create.addColumn(columnName, columnDescription.get(columnName).getLeft());
+ }
+ log.trace("exacuting :{}", create.toString());
+ ResultSet result = session.execute(create);
+ log.info("table:{} created succsesfully.", tableName);
+ } else {
+ log.info("table:{} already exists skiping.", tableName);
+ }
+ List<String> indexNames = (keyspaceMetadate != null ? keyspaceMetadate.get(tableName) : new ArrayList<>());
+ log.info("table:{} creating indexes.", tableName);
+ for (String columnName : columnDescription.keySet()) {
+ String indexName = createIndexName(tableName, columnName).toLowerCase();
+ if (columnDescription.get(columnName).getRight()) {
+ if (!indexNames.contains(indexName)) {
+ SchemaStatement creatIndex = SchemaBuilder.createIndex(indexName)
+ .onTable(tableDescription.getKeyspace(), tableName).andColumn(columnName);
+ log.info("executing :{}", creatIndex.toString());
+ session.execute(creatIndex);
+ log.info("index:{} created succsesfully.", indexName);
+ } else {
+ log.info("index:{} already exists skiping.", indexName);
+ }
+ }
+ }
+
+ }
+ }
+
+ /**
+ * the method create the keyspace in case it does not already exists the
+ * method uses configurtion to select the needed replication strategy
+ *
+ * @param keyspace
+ * name of the keyspace we want to create
+ * @param cassndraMetadata
+ * cassndra metadata
+ * @param session
+ * the session object used for the execution of the query.
+ * @return true in case the operation was successful
+ */
+ private static boolean createKeyspace(String keyspace, Map<String, Map<String, List<String>>> cassndraMetadata,
+ Session session) {
+ List<Configuration.CassandrConfig.KeyspaceConfig> keyspaceConfigList = ConfigurationManager
+ .getConfigurationManager().getConfiguration().getCassandraConfig().getKeySpaces();
+ log.info("creating keyspace:{}.", keyspace);
+ if (!cassndraMetadata.keySet().contains(keyspace)) {
+ Optional<Configuration.CassandrConfig.KeyspaceConfig> keyspaceConfig = keyspaceConfigList.stream()
+ .filter(keyspaceInfo -> keyspace.equalsIgnoreCase(keyspaceInfo.getName())).findFirst();
+ if (keyspaceConfig.isPresent()) {
+ Configuration.CassandrConfig.KeyspaceConfig keyspaceInfo = keyspaceConfig.get();
+ String createKeyspaceQuery = createKeyspaceQuereyString(keyspace, keyspaceInfo);
+ if (createKeyspaceQuery != null) {
+ log.trace("exacuting: {}", createKeyspaceQuery);
+ session.execute(createKeyspaceQuery);
+ log.info("keyspace:{} created.", keyspace);
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ log.info(
+ "keyspace:{} not present in configuration, no info on replications is available. operation failed.",
+ keyspace);
+ return false;
+ }
+ } else {
+ log.info("keyspace:{} already exists skipping.", keyspace);
+ return true;
+ }
+ }
+
+ /**
+ * the method retries the schem info from the enums describing the tables
+ *
+ * @return a map of keyspaces to there table info
+ */
+ private static Map<String, List<ITableDescription>> getSchemeData() {
+ Map<String, List<ITableDescription>> tablesByKeyspace = new HashMap<String, List<ITableDescription>>();
+ Table[] tables = Table.values();
+ for (Table table : tables) {
+ String keyspace = table.getTableDescription().getKeyspace().toLowerCase();
+ List<ITableDescription> list = tablesByKeyspace.get(keyspace);
+ if (list == null) {
+ list = new ArrayList<>();
+ }
+ list.add(table.getTableDescription());
+ tablesByKeyspace.put(keyspace, list);
+ }
+ return tablesByKeyspace;
+ }
+
+ /**
+ * the methoed creates the query string for the given keyspace the methoed
+ * valides the given data according the the requirments of the replication
+ * strategy SimpleStrategy: "CREATE KEYSPACE IF NOT EXISTS
+ * <keyspaceName></keyspaceName> WITH replication =
+ * {'class':'SimpleStrategy', 'replication_factor':2};" SimpleStrategy:
+ * "CREATE KEYSPACE IF NOT EXISTS <keyspaceName></keyspaceName> WITH
+ * replication = {'class':'NetworkTopologyStrategy', 'dc1' : 2 ,dc2 : 2 };"
+ *
+ * @param keyspace
+ * name of the keyspace we want to create
+ * @param keyspaceInfo
+ * configuration info regurding the replication of the keyspace
+ * @return a querey string for the creation of the keyspace
+ */
+ private static String createKeyspaceQuereyString(String keyspace,
+ Configuration.CassandrConfig.KeyspaceConfig keyspaceInfo) {
+ String query = null;
+ if (ReplicationStrategy.NETWORK_TOPOLOGY_STRATEGY.getName()
+ .equalsIgnoreCase(keyspaceInfo.getReplicationStrategy())) {
+ List<String> dcList = keyspaceInfo.getReplicationInfo();
+ if (dcList.size() % 2 != 0) {
+ log.error("the supplied replication info is in valid expected dc1,2,dc2,2 etc received:{}", dcList);
+ return query;
+ }
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < dcList.size(); i = i + 2) {
+ sb.append("'").append(dcList.get(i)).append("'").append(" : ").append(dcList.get(i + 1));
+ if (i + 2 < dcList.size()) {
+ sb.append(",");
+ }
+ }
+
+ query = String.format(CREATE_KEYSPACE_NETWORK_TOPOLOGY_STRATEGY, keyspace, sb.toString());
+ } else if (ReplicationStrategy.SIMPLE_STRATEGY.getName()
+ .equalsIgnoreCase(keyspaceInfo.getReplicationStrategy())) {
+ List<String> dcList = keyspaceInfo.getReplicationInfo();
+ if (dcList.size() != 1) {
+ log.error("the supplied replication info is in valid expected <number> etc received:{}", dcList);
+ return query;
+ }
+ StringBuilder sb = new StringBuilder();
+ sb.append("'replication_factor'").append(" : ").append(dcList.get(0));
+ query = String.format(CREATE_KEYSPACE_SIMPLE_STRATEGY, keyspace, sb.toString());
+
+ } else {
+ log.error("the suplied replication Strategy is in valide expacted {}/{} etc recived:{}",
+ ReplicationStrategy.NETWORK_TOPOLOGY_STRATEGY.getName(),
+ ReplicationStrategy.SIMPLE_STRATEGY.getName(), keyspaceInfo.getReplicationStrategy());
+ }
+ return query;
+ }
+
+ public enum ReplicationStrategy {
+ NETWORK_TOPOLOGY_STRATEGY("NetworkTopologyStrategy"), SIMPLE_STRATEGY("SimpleStrategy");
+
+ public String name;
+
+ private ReplicationStrategy(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java
new file mode 100644
index 0000000000..6de40a7117
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java
@@ -0,0 +1,71 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema;
+
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.ArtifactTableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.AuthEventTableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.CategoryEventTableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.ComponentCacheTableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.ConsumerEventTableDefinition;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribDeployEventTableDesc;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribDownloadEventTableDesc;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribEngineEventTableDesc;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribNotifEventTableDesc;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribStatusEventTableDesc;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.ExternalApiEventTableDesc;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetCatHierEventTableDesc;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUebClusterEventTableDesc;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUsersListEventTableDesc;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.ResAdminEventTableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAccessEventTableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAdminEventTableDescription;
+
+public enum Table {
+
+ ARTIFACT(new ArtifactTableDescription()),
+ USER_ADMIN_EVENT(new UserAdminEventTableDescription()),
+ USER_ACCESS_EVENT(new UserAccessEventTableDescription()),
+ RESOURCE_ADMIN_EVENT(new ResAdminEventTableDescription()),
+ DISTRIBUTION_DOWNLOAD_EVENT(new DistribDownloadEventTableDesc()),
+ DISTRIBUTION_ENGINE_EVENT(new DistribEngineEventTableDesc()),
+ DISTRIBUTION_NOTIFICATION_EVENT(new DistribNotifEventTableDesc()),
+ DISTRIBUTION_STATUS_EVENT(new DistribStatusEventTableDesc()),
+ DISTRIBUTION_DEPLOY_EVENT(new DistribDeployEventTableDesc()),
+ DISTRIBUTION_GET_UEB_CLUSTER_EVENT(new GetUebClusterEventTableDesc()),
+ AUTH_EVENT(new AuthEventTableDescription()),
+ CONSUMER_EVENT(new ConsumerEventTableDefinition()),
+ CATEGORY_EVENT(new CategoryEventTableDescription()),
+ GET_USERS_LIST_EVENT(new GetUsersListEventTableDesc()),
+ GET_CATEGORY_HIERARCHY_EVENT(new GetCatHierEventTableDesc()),
+ EXTERNAL_API_EVENT(new ExternalApiEventTableDesc()),
+ COMPONENT_CACHE(new ComponentCacheTableDescription());
+
+ ITableDescription tableDescription;
+
+ Table(ITableDescription tableDescription) {
+ this.tableDescription = tableDescription;
+ }
+
+ public ITableDescription getTableDescription() {
+ return tableDescription;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java
new file mode 100644
index 0000000000..2e26bd2675
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java
@@ -0,0 +1,95 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+import java.util.*;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class ArtifactTableDescription implements ITableDescription {
+
+ private static final String keyspaceType = "artifact";
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(ID_FIELD, DataType.varchar()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (ArtifactFieldsDescription field : ArtifactFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.ARTIFACT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return "resources";
+ }
+
+ enum ArtifactFieldsDescription {
+ DATA("data", DataType.blob(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ ArtifactFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ return null;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java
new file mode 100644
index 0000000000..ef7be5deb7
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java
@@ -0,0 +1,103 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAdminEventTableDescription.UAEFieldsDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+import com.datastax.driver.mapping.annotations.Column;
+
+public class AuthEventTableDescription implements ITableDescription {
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (AEFieldsDescription field : AEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.AUTH_EVENT_TYPE;
+ }
+
+ enum AEFieldsDescription {
+
+ URL("url", DataType.varchar(), false), REQUEST_ID("request_id", DataType.varchar(), true), USER("user",
+ DataType.varchar(), false), AUTH_STATUS("auth_status", DataType.varchar(), false), REALM("realm",
+ DataType.varchar(), false), ACTION("action", DataType.varchar(), true), STATUS("status",
+ DataType.varchar(), false), DESC("description", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ AEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java
new file mode 100644
index 0000000000..efefac57b6
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java
@@ -0,0 +1,105 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+import com.datastax.driver.mapping.annotations.Column;
+
+public class CategoryEventTableDescription implements ITableDescription {
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (CEFieldsDescription field : CEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.CATEGORY_EVENT_TYPE;
+ }
+
+ enum CEFieldsDescription {
+
+ ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESC("description",
+ DataType.varchar(), false), CATEGORY_NAME("category_Name", DataType.varchar(),
+ false), SUB_CATEGORY_NAME("sub_Category_Name", DataType.varchar(), false), GROUPING_NAME(
+ "grouping_name", DataType.varchar(), false), MODIFIER("modifier", DataType.varchar(),
+ false), REQUEST_ID("request_id", DataType.varchar(), false), RESOURCE_TYPE(
+ "resource_type", DataType.varchar(), false), SERVICE_INSTANCE_ID(
+ "service_instance_id", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ CEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java
new file mode 100644
index 0000000000..6396da5c32
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java
@@ -0,0 +1,95 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+import java.util.*;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class ComponentCacheTableDescription implements ITableDescription {
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(ID_FIELD, DataType.varchar()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (PartialComponentFieldsDescription field : PartialComponentFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.COMPONENT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return "componentcache";
+ }
+
+ enum PartialComponentFieldsDescription {
+ DATA("data", DataType.blob(), false), MODIFICATION_TIME("modification_time", DataType.timestamp(), false), TYPE(
+ "type", DataType.varchar(), false), IS_DIRTY("is_dirty", DataType.cboolean(),
+ false), IS_ZIPPED("is_zipped", DataType.cboolean(), false),;
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ PartialComponentFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ return null;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java
new file mode 100644
index 0000000000..554a7a7a51
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java
@@ -0,0 +1,101 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUebClusterEventTableDesc.DEEFieldsDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class ConsumerEventTableDefinition implements ITableDescription {
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (DEEFieldsDescription field : DEEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.CONSUMER_EVENT_TYPE;
+ }
+
+ enum DEEFieldsDescription {
+ ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
+ "description", DataType.varchar(),
+ false), ECOMP_USER("ecomp_user", DataType.varchar(), false), MODIFIER("modifier", DataType.varchar(),
+ false), REQUEST_ID("request_id", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ DEEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java
new file mode 100644
index 0000000000..5fc1dc8bd4
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java
@@ -0,0 +1,104 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribDownloadEventTableDesc.DSEFieldsDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class DistribDeployEventTableDesc implements ITableDescription {
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (DSEFieldsDescription field : DSEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE;
+ }
+
+ enum DSEFieldsDescription {
+ ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), true), DESCRIPTION(
+ "description", DataType.varchar(), false), REQUEST_ID("request_id", DataType.varchar(),
+ false), SERVICE_INST_ID("service_instance_id", DataType.varchar(), true), MODIFIER("modifier",
+ DataType.varchar(), false), CURR_VERSION("curr_version", DataType.varchar(),
+ false), DID("did", DataType.varchar(), true), RESOURCE_NAME("resource_name",
+ DataType.varchar(),
+ false), RESOURCE_TYPE("resource_type", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ DSEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java
new file mode 100644
index 0000000000..0ed4f55a7b
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java
@@ -0,0 +1,100 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class DistribDownloadEventTableDesc implements ITableDescription {
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (DSEFieldsDescription field : DSEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.DISTRIBUTION_DOWNLOAD_EVENT_TYPE;
+ }
+
+ enum DSEFieldsDescription {
+ REQUEST_ID("request_Id", DataType.varchar(), false), SERVICE_INST_ID("service_Instance_Id", DataType.varchar(),
+ false), ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(),
+ false), DESCRIPTION("description", DataType.varchar(), false), CONSUMER_ID("consumer_Id",
+ DataType.varchar(), false), RESOURCE_URL("resource_URL", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ DSEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java
new file mode 100644
index 0000000000..5ce5bffb7c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java
@@ -0,0 +1,103 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class DistribEngineEventTableDesc implements ITableDescription {
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (DEEFieldsDescription field : DEEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE;
+ }
+
+ enum DEEFieldsDescription {
+ ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
+ "description", DataType.varchar(),
+ false), CONSUMER_ID("consumer_id", DataType.varchar(), false), REQUEST_ID("request_id",
+ DataType.varchar(), true), SERVICE_INST_ID("service_instance_id", DataType.varchar(),
+ false), ROLE("role", DataType.varchar(), false), D_ENV("d_env", DataType.varchar(),
+ false), API_KEY("api_key", DataType.varchar(), false), DSTATUS_TOPIC(
+ "dstatus_topic", DataType.varchar(),
+ false), DNOTIF_TOPIC("dnotif_topic", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ DEEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java
new file mode 100644
index 0000000000..96fab66701
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java
@@ -0,0 +1,104 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class DistribNotifEventTableDesc implements ITableDescription {
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (DNEFieldsDescription field : DNEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.DISTRIBUTION_NOTIFICATION_EVENT_TYPE;
+ }
+
+ enum DNEFieldsDescription {
+ ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
+ "description", DataType.varchar(),
+ false), REQUEST_ID("request_id", DataType.varchar(), false), SERVICE_INST_ID("service_instance_id",
+ DataType.varchar(), true), TOPIC_NAME("topic_name", DataType.varchar(), false), MODIFIER(
+ "modifier", DataType.varchar(), false), CURR_STATE("curr_state", DataType.varchar(),
+ false), CURR_VERSION("curr_version", DataType.varchar(), false), DID("did",
+ DataType.varchar(), true), RESOURCE_NAME("resource_name",
+ DataType.varchar(), false), RESOURCE_TYPE("resource_type",
+ DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ DNEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java
new file mode 100644
index 0000000000..bc564e3743
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java
@@ -0,0 +1,102 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class DistribStatusEventTableDesc implements ITableDescription {
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (DSEFieldsDescription field : DSEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.DISTRIBUTION_STATUS_EVENT_TYPE;
+ }
+
+ enum DSEFieldsDescription {
+ ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
+ "description", DataType.varchar(),
+ false), DID("did", DataType.varchar(), true), CONSUMER_ID("consumer_id", DataType.varchar(),
+ false), REQUEST_ID("request_id", DataType.varchar(), false), RESOURCE_URL("resoure_URL",
+ DataType.varchar(), false), SERVICE_INST_ID("service_instance_id", DataType.varchar(),
+ false), TOPIC_NAME("topic_name", DataType.varchar(),
+ false), STATUS_TIME("status_time", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ DSEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java
new file mode 100644
index 0000000000..a67c9ef4ef
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java
@@ -0,0 +1,104 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class ExternalApiEventTableDesc implements ITableDescription {
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (EGAEFieldsDescription field : EGAEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE;
+ }
+
+ enum EGAEFieldsDescription {
+ ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
+ "description", DataType.varchar(), false), CONSUMER_ID("consumer_id", DataType.varchar(),
+ false), RESOURCE_URL("resource_URL", DataType.varchar(), false), RESOURCE_NAME("resource_name",
+ DataType.varchar(),
+ false), RESOURCE_TYPE("resource_type", DataType.varchar(), false), SERVICE_INST_ID(
+ "service_instance_id", DataType.varchar(),
+ true), MODIFIER("modifier", DataType.varchar(), false), PREV_ARTIFACT_UUID(
+ "prev_artifact_uuid", DataType.varchar(), false), CURR_ARTIFACT_UUID(
+ "curr_artifact_uuid", DataType.varchar(), false), ARTIFACT_DATA(
+ "artifact_data", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ EGAEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java
new file mode 100644
index 0000000000..2d1a5c3c75
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java
@@ -0,0 +1,99 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUsersListEventTableDesc.DEEFieldsDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class GetCatHierEventTableDesc implements ITableDescription {
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (DEEFieldsDescription field : DEEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.GET_CATEGORY_HIERARCHY_EVENT_TYPE;
+ }
+
+ enum DEEFieldsDescription {
+ ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
+ "description", DataType.varchar(), false), DETAILS("details", DataType.varchar(), false), REQUEST_ID(
+ "request_id", DataType.varchar(), false), MODIFIER("modifier", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ DEEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java
new file mode 100644
index 0000000000..8ef1f01186
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java
@@ -0,0 +1,101 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribEngineEventTableDesc.DEEFieldsDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class GetUebClusterEventTableDesc implements ITableDescription {
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (DEEFieldsDescription field : DEEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE;
+ }
+
+ enum DEEFieldsDescription {
+ ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
+ "description", DataType.varchar(),
+ false), CONSUMER_ID("consumer_Id", DataType.varchar(), false), REQUEST_ID("request_Id",
+ DataType.varchar(), false), SERVICE_INST_ID("service_Instance_Id", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ DEEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java
new file mode 100644
index 0000000000..5d94bd3f4d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java
@@ -0,0 +1,99 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUebClusterEventTableDesc.DEEFieldsDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class GetUsersListEventTableDesc implements ITableDescription {
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (DEEFieldsDescription field : DEEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.GET_USERS_LIST_EVENT_TYPE;
+ }
+
+ enum DEEFieldsDescription {
+ ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION(
+ "description", DataType.varchar(), false), DETAILS("details", DataType.varchar(), false), REQUEST_ID(
+ "request_id", DataType.varchar(), false), MODIFIER("modifier", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ DEEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java
new file mode 100644
index 0000000000..a6f0ba905d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java
@@ -0,0 +1,132 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+import com.datastax.driver.mapping.annotations.Column;
+
+public class ResAdminEventTableDescription implements ITableDescription {
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (AEFieldsDescription field : AEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE;
+ }
+
+ enum AEFieldsDescription {
+ REQUEST_ID("request_id", DataType.varchar(), false), SERVICE_INST_ID("service_instance_id", DataType.varchar(),
+ true), INVARIANT_UUID("invariant_UUID", DataType.varchar(), true), ACTION("action", DataType.varchar(),
+ true), STATUS("status", DataType.varchar(), false), DESCRIPTION("description",
+ DataType.varchar(),
+ false), RESOURCE_TYPE("resource_type", DataType.varchar(), false), PREV_VERSION(
+ "prev_version", DataType.varchar(),
+ true), PREV_STATE("prev_state", DataType.varchar(), true), CURR_STATE(
+ "curr_state", DataType.varchar(), false), RESOURCE_NAME("resource_name",
+ DataType.varchar(), false), CURR_VERSION("curr_version",
+ DataType.varchar(), true), MODIFIER("modifier",
+ DataType.varchar(),
+ false), PREV_ARTIFACT_UUID("prev_artifact_UUID",
+ DataType.varchar(),
+ false), CURR__ARTIFACT_UUID(
+ "curr_artifact_UUID",
+ DataType.varchar(),
+ false), ARTIFACT_DATA(
+ "artifact_data",
+ DataType.varchar(),
+ false), DID("did",
+ DataType.varchar(),
+ true), DPREV_STATUS(
+ "dprev_status",
+ DataType.varchar(),
+ false), DCURR_STATUS(
+ "dcurr_status",
+ DataType.varchar(),
+ false), TOSCA_NODE_TYPE(
+ "tosca_node_type",
+ DataType.varchar(),
+ false), COMMENT(
+ "comment",
+ DataType.varchar(),
+ false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ AEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java
new file mode 100644
index 0000000000..7f482ae3ac
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java
@@ -0,0 +1,104 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+import com.datastax.driver.mapping.annotations.Column;
+
+public class UserAccessEventTableDescription implements ITableDescription {
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (UAEFieldsDescription field : UAEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.USER_ACCESS_EVENT_TYPE;
+ }
+
+ enum UAEFieldsDescription {
+ REQUEST_ID("request_Id", DataType.varchar(), false), USER("USER", DataType.varchar(), false), ACTION("action",
+ DataType.varchar(), true), STATUS("status", DataType.varchar(), false), DESCRIPTION("description",
+ DataType.varchar(),
+ false), SERVICE_INSTANCE_ID("service_instance_id", DataType.varchar(), false);
+
+ @Column
+ private String modifier;
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ UAEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAdminEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAdminEventTableDescription.java
new file mode 100644
index 0000000000..dd8df08cdd
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAdminEventTableDescription.java
@@ -0,0 +1,102 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+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.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import com.datastax.driver.core.DataType;
+
+public class UserAdminEventTableDescription implements ITableDescription {
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (UAEFieldsDescription field : UAEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.USER_ADMIN_EVENT_TYPE;
+ }
+
+ enum UAEFieldsDescription {
+ REQUEST_ID("request_id", DataType.varchar(), false), SERVICE_INST_ID("service_instance_id", DataType.varchar(),
+ false), ACTION("action", DataType.varchar(), true), STATUS("status", DataType.varchar(),
+ false), DESCRIPTION("description", DataType.varchar(), false), MODIFIER("modifier",
+ DataType.varchar(), false), USER_BEFORE("user_before", DataType.varchar(),
+ false), USER_AFTER("user_after", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ UAEFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java
new file mode 100644
index 0000000000..1c3ba1107f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java
@@ -0,0 +1,226 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.es;
+
+import java.net.InetSocketAddress;
+import java.net.MalformedURLException;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+
+import org.apache.commons.lang.SystemUtils;
+import org.elasticsearch.action.admin.cluster.health.ClusterHealthAction;
+import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequestBuilder;
+import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
+import org.elasticsearch.client.Client;
+import org.elasticsearch.client.transport.TransportClient;
+import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.common.transport.InetSocketTransportAddress;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.node.Node;
+import org.elasticsearch.node.NodeBuilder;
+import org.elasticsearch.shield.ShieldPlugin;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+/**
+ * Prepare the node to work with elastic search.
+ *
+ * @author luc boutier
+ */
+@Component("elasticsearch-client")
+public class ElasticSearchClient {
+
+ private static Logger log = LoggerFactory.getLogger(ElasticSearchClient.class.getName());
+
+ private Node node;
+ private boolean isLocal;
+ private String clusterName;
+ private Client client;
+
+ String serverHost;
+ String serverPort;
+
+ ArrayList<String> nodes = new ArrayList<String>();
+
+ private boolean isTransportClient;
+
+ @PostConstruct
+ public void initialize() throws URISyntaxException {
+
+ URL url = null;
+ Settings settings = null;
+ URL systemResourceElasticsearchPath = ClassLoader.getSystemResource("elasticsearch.yml");
+
+ if (systemResourceElasticsearchPath != null) {
+ log.debug("try to create URI for {}", systemResourceElasticsearchPath.toString());
+ Path classpathConfig = Paths.get(systemResourceElasticsearchPath.toURI());
+ settings = Settings.settingsBuilder().loadFromPath(classpathConfig).build();
+ }
+ String configHome = System.getProperty("config.home");
+ if (configHome != null && false == configHome.isEmpty()) {
+ try {
+ if (SystemUtils.IS_OS_WINDOWS) {
+ url = new URL("file:///" + configHome + "/elasticsearch.yml");
+ } else {
+ url = new URL("file:" + configHome + "/elasticsearch.yml");
+ }
+
+ log.debug("URL {}", url);
+ settings = Settings.settingsBuilder().loadFromPath(Paths.get(url.toURI())).build();
+ } catch (MalformedURLException | URISyntaxException e1) {
+ log.error("Failed to create URL in order to load elasticsearch yml");
+ System.err.println("Failed to create URL in order to load elasticsearch yml from " + configHome);
+ }
+ }
+ if (settings == null) {
+ log.error("Failed to find settings of elasticsearch yml");
+ System.err.println("Failed to create URL in order to load elasticsearch yml from " + configHome);
+ }
+ if (isTransportClient()) {
+ log.info("******* ElasticSearchClient type is Transport Client *****");
+ TransportClient transportClient = TransportClient.builder().addPlugin(ShieldPlugin.class).settings(settings)
+ .build();
+
+ String[] nodesArray = transportClient.settings().getAsArray("transport.client.initial_nodes");
+ for (String host : nodesArray) {
+ int port = 9300;
+
+ // or parse it from the host string...
+ String[] splitHost = host.split(":", 2);
+ if (splitHost.length == 2) {
+ host = splitHost[0];
+ port = Integer.parseInt(splitHost[1]);
+ }
+
+ transportClient.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(host, port)));
+
+ }
+ this.client = transportClient;
+ serverHost = Arrays.toString(nodesArray);
+
+ } else {
+ log.info("******* ElasticSearchClient type is Node Client *****");
+ this.node = NodeBuilder.nodeBuilder().settings(settings).client(!isLocal).clusterName(this.clusterName)
+ .local(isLocal).node();
+ this.client = node.client();
+
+ serverHost = this.client.settings().get("discovery.zen.ping.unicast.hosts");
+ if (serverHost == null) {
+ serverHost = "['localhost:9200']";
+ }
+
+ }
+
+ serverPort = this.client.settings().get("http.port");
+ if (serverPort == null) {
+ serverPort = "9200";
+ }
+
+ log.info("Initialized ElasticSearch client for cluster <{}> with nodes: {}", this.clusterName, serverHost);
+ }
+
+ @PreDestroy
+ public void close() {
+ if (client != null) {
+ client.close();
+ }
+ if (node != null) {
+ node.close();
+ }
+ log.info("Closed ElasticSearch client for cluster <" + this.clusterName + ">");
+ }
+
+ /**
+ * Get the elastic search client.
+ *
+ * @return The elastic search client.
+ */
+ public Client getClient() {
+ return this.client;
+ }
+
+ public String getServerHost() {
+ return serverHost;
+ }
+
+ public String getServerPort() {
+ return serverPort;
+ }
+
+ /**
+ * Wait for green status for the given indices.
+ *
+ * @param indices
+ * The indices to wait for.
+ * @return A {@link ClusterHealthResponse} that contains the cluster health
+ * after waiting maximum 5 minutes for green status.
+ */
+ public ClusterHealthResponse waitForGreenStatus(String... indices) {
+ ClusterHealthAction healthAction = ClusterHealthAction.INSTANCE;
+
+ ClusterHealthRequestBuilder builder = healthAction.newRequestBuilder(this.client.admin().cluster());
+ builder.setIndices(indices);
+ builder.setWaitForGreenStatus();
+ builder.setTimeout(TimeValue.timeValueSeconds(30));
+ ClusterHealthResponse response = builder.execute().actionGet();
+ log.debug("getStatus : {}", response.getStatus());
+ log.debug("getActivePrimaryShards : {}", response.getActivePrimaryShards());
+ log.debug("getActiveShards : {}", response.getActiveShards());
+ log.debug("getInitializingShards : {}", response.getInitializingShards());
+ log.debug("getNumberOfDataNodes : {}", response.getNumberOfDataNodes());
+ log.debug("getNumberOfNodes : {}", response.getNumberOfNodes());
+ log.debug("getRelocatingShards : {}", response.getRelocatingShards());
+ log.debug("getUnassignedShards : {}", response.getUnassignedShards());
+ log.debug("getAllValidationFailures : {}", response.getAllValidationFailures());
+ return response;
+ }
+
+ @Value("#{elasticsearchConfig['cluster.name']}")
+ public void setClusterName(final String clusterName) {
+ this.clusterName = clusterName;
+ }
+
+ @Value("#{elasticsearchConfig['elasticSearch.local']}")
+ public void setLocal(final String strIsLocal) {
+ if (strIsLocal != null && !strIsLocal.isEmpty())
+ this.isLocal = Boolean.parseBoolean(strIsLocal);
+ }
+
+ public boolean isTransportClient() {
+ return isTransportClient;
+ }
+
+ @Value("#{elasticsearchConfig['elasticSearch.transportclient']}")
+ public void setTransportClient(final String strIsTransportclient) {
+ if (strIsTransportclient != null && !strIsTransportclient.isEmpty())
+ this.isTransportClient = Boolean.parseBoolean(strIsTransportclient);
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java
new file mode 100644
index 0000000000..bf93c23afc
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java
@@ -0,0 +1,264 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.graph;
+
+import java.util.Map;
+
+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.graph.datatype.RelationEndPoint;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.resources.data.AdditionalInfoParameterData;
+import org.openecomp.sdc.be.resources.data.ArtifactData;
+import org.openecomp.sdc.be.resources.data.AttributeData;
+import org.openecomp.sdc.be.resources.data.AttributeValueData;
+import org.openecomp.sdc.be.resources.data.CapabilityData;
+import org.openecomp.sdc.be.resources.data.CapabilityInstData;
+import org.openecomp.sdc.be.resources.data.CapabilityTypeData;
+import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
+import org.openecomp.sdc.be.resources.data.ConsumerData;
+import org.openecomp.sdc.be.resources.data.DataTypeData;
+import org.openecomp.sdc.be.resources.data.GraphNodeLock;
+import org.openecomp.sdc.be.resources.data.GroupData;
+import org.openecomp.sdc.be.resources.data.GroupTypeData;
+import org.openecomp.sdc.be.resources.data.HeatParameterData;
+import org.openecomp.sdc.be.resources.data.HeatParameterValueData;
+import org.openecomp.sdc.be.resources.data.InputValueData;
+import org.openecomp.sdc.be.resources.data.InputsData;
+import org.openecomp.sdc.be.resources.data.InterfaceData;
+import org.openecomp.sdc.be.resources.data.OperationData;
+import org.openecomp.sdc.be.resources.data.PolicyTypeData;
+import org.openecomp.sdc.be.resources.data.ProductMetadataData;
+import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
+import org.openecomp.sdc.be.resources.data.RelationshipInstData;
+import org.openecomp.sdc.be.resources.data.RequirementData;
+import org.openecomp.sdc.be.resources.data.RequirementImplData;
+import org.openecomp.sdc.be.resources.data.ResourceCategoryData;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
+import org.openecomp.sdc.be.resources.data.ServiceCategoryData;
+import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
+import org.openecomp.sdc.be.resources.data.TagData;
+import org.openecomp.sdc.be.resources.data.UserData;
+import org.openecomp.sdc.be.resources.data.UserFunctionalMenuData;
+import org.openecomp.sdc.be.resources.data.category.CategoryData;
+import org.openecomp.sdc.be.resources.data.category.GroupingData;
+import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
+
+public class GraphElementFactory {
+
+ public static <T extends GraphNode> T createElement(String label, GraphElementTypeEnum type,
+ Map<String, Object> properties, Class<T> clazz) {
+ T element = null;
+
+ if (type.equals(GraphElementTypeEnum.Node)) {
+ element = createNode(label, properties, clazz);
+ }
+ return element;
+ }
+
+ public static GraphNode createElement(String label, GraphElementTypeEnum type, Map<String, Object> properties) {
+ GraphNode element = null;
+
+ if (type.equals(GraphElementTypeEnum.Node)) {
+ element = createNode(label, properties);
+ }
+ return element;
+ }
+
+ public static GraphRelation createRelation(String type, Map<String, Object> properties, GraphNode from,
+ GraphNode to) {
+ GraphRelation element = new GraphRelation(type);
+ RelationEndPoint endPOintFrom = new RelationEndPoint(NodeTypeEnum.getByName(from.getLabel()),
+ from.getUniqueIdKey(), from.getUniqueId());
+ RelationEndPoint endPOintTo = new RelationEndPoint(NodeTypeEnum.getByName(to.getLabel()), to.getUniqueIdKey(),
+ to.getUniqueId());
+ element.setFrom(endPOintFrom);
+ element.setTo(endPOintTo);
+ element.addPropertis(properties);
+ return element;
+ }
+
+ private static GraphNode createNode(String label, Map<String, Object> properties) {
+ GraphNode element = null;
+ NodeTypeEnum type = NodeTypeEnum.getByName(label);
+ if (type != null) {
+ switch (type) {
+ case User:
+ element = new UserData(properties);
+ break;
+ case ResourceCategory:
+ element = new ResourceCategoryData(properties);
+ break;
+ case ServiceCategory:
+ element = new ServiceCategoryData(properties);
+ break;
+ case Tag:
+ element = new TagData(properties);
+ break;
+ case Service:
+ element = new ServiceMetadataData(properties);
+ break;
+ case Resource:
+ element = new ResourceMetadataData(properties);
+ break;
+ case Property:
+ element = new PropertyData(properties);
+ break;
+ case HeatParameter:
+ element = new HeatParameterData(properties);
+ break;
+ case HeatParameterValue:
+ element = new HeatParameterValueData(properties);
+ break;
+ }
+ }
+ return element;
+ }
+
+ private static <T extends GraphNode> T createNode(String label, Map<String, Object> properties, Class<T> clazz) {
+ T element = null;
+ NodeTypeEnum type = NodeTypeEnum.getByName(label);
+ if (type != null) {
+ switch (type) {
+ case User:
+ element = clazz.cast(new UserData(properties));
+ break;
+ case ResourceCategory:
+ element = clazz.cast(new ResourceCategoryData(properties));
+ break;
+ case ServiceCategory:
+ element = clazz.cast(new ServiceCategoryData(properties));
+ break;
+ case ResourceNewCategory:
+ case ServiceNewCategory:
+ case ProductCategory:
+ element = clazz.cast(new CategoryData(properties));
+ break;
+ case ResourceSubcategory:
+ case ProductSubcategory:
+ element = clazz.cast(new SubCategoryData(properties));
+ break;
+ case ProductGrouping:
+ element = clazz.cast(new GroupingData(properties));
+ break;
+ case Tag:
+ element = clazz.cast(new TagData(properties));
+ break;
+ case Service:
+ element = clazz.cast(new ServiceMetadataData(properties));
+ break;
+ case Product:
+ element = clazz.cast(new ProductMetadataData(properties));
+ break;
+ case Resource:
+ element = clazz.cast(new ResourceMetadataData(properties));
+ break;
+ case Attribute:
+ element = clazz.cast(new AttributeData(properties));
+ break;
+ case Property:
+ element = clazz.cast(new PropertyData(properties));
+ break;
+ case CapabilityType:
+ element = clazz.cast(new CapabilityTypeData(properties));
+ break;
+ case Requirement:
+ element = clazz.cast(new RequirementData(properties));
+ break;
+ case RequirementImpl:
+ element = clazz.cast(new RequirementImplData(properties));
+ break;
+ case Capability:
+ element = clazz.cast(new CapabilityData(properties));
+ break;
+ case CapabilityInst:
+ element = clazz.cast(new CapabilityInstData(properties));
+ break;
+ case PropertyValue:
+ element = clazz.cast(new PropertyValueData(properties));
+ break;
+ case AttributeValue:
+ element = clazz.cast(new AttributeValueData(properties));
+ break;
+ case InputValue:
+ element = clazz.cast(new InputValueData(properties));
+ break;
+ case RelationshipType:
+ break;
+ case LockNode:
+ element = clazz.cast(new GraphNodeLock(properties));
+ break;
+ case ArtifactRef:
+ element = clazz.cast(new ArtifactData(properties));
+ break;
+ case Interface:
+ element = clazz.cast(new InterfaceData(properties));
+ break;
+ case InterfaceOperation:
+ element = clazz.cast(new OperationData(properties));
+ break;
+ case Input:
+ element = clazz.cast(new InputsData(properties));
+ break;
+ case ResourceInstance:
+ element = clazz.cast(new ComponentInstanceData(properties));
+ break;
+ case RelationshipInst:
+ element = clazz.cast(new RelationshipInstData(properties));
+ break;
+ case AdditionalInfoParameters:
+ element = clazz.cast(new AdditionalInfoParameterData(properties));
+ break;
+ case ConsumerCredentials:
+ element = clazz.cast(new ConsumerData(properties));
+ break;
+ case HeatParameter:
+ element = clazz.cast(new HeatParameterData(properties));
+ break;
+ case HeatParameterValue:
+ element = clazz.cast(new HeatParameterValueData(properties));
+ break;
+ case DataType:
+ element = clazz.cast(new DataTypeData(properties));
+ break;
+ case Group:
+ element = clazz.cast(new GroupData(properties));
+ break;
+ case GroupType:
+ element = clazz.cast(new GroupTypeData(properties));
+ break;
+ case UserFunctionalMenu:
+ element = clazz.cast(new UserFunctionalMenuData(properties));
+ break;
+ case PolicyType:
+ element = clazz.cast(new PolicyTypeData(properties));
+ break;
+ default:
+ break;
+ }
+
+ }
+ return element;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/ActionEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/ActionEnum.java
new file mode 100644
index 0000000000..13ef58ddf5
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/ActionEnum.java
@@ -0,0 +1,25 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.graph.datatype;
+
+public enum ActionEnum {
+ Create, Update, Delete, NoAction
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/AdditionalInformationEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/AdditionalInformationEnum.java
new file mode 100644
index 0000000000..ea59ef81ac
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/AdditionalInformationEnum.java
@@ -0,0 +1,25 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.graph.datatype;
+
+public enum AdditionalInformationEnum {
+ Label, Value, None;
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphEdge.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphEdge.java
new file mode 100644
index 0000000000..4555f9f9ea
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphEdge.java
@@ -0,0 +1,94 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.graph.datatype;
+
+import java.util.Map;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+
+public class GraphEdge {
+
+ private GraphEdgeLabels edgeType;
+
+ private Map<String, Object> properties;
+
+ public GraphEdge() {
+ super();
+ }
+
+ public GraphEdge(GraphEdgeLabels edgeType, Map<String, Object> properties) {
+ super();
+ this.edgeType = edgeType;
+ this.properties = properties;
+ }
+
+ public GraphEdgeLabels getEdgeType() {
+ return edgeType;
+ }
+
+ public void setEdgeType(GraphEdgeLabels edgeType) {
+ this.edgeType = edgeType;
+ }
+
+ public Map<String, Object> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(Map<String, Object> properties) {
+ this.properties = properties;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((edgeType == null) ? 0 : edgeType.hashCode());
+ result = prime * result + ((properties == null) ? 0 : properties.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ GraphEdge other = (GraphEdge) obj;
+ if (edgeType != other.edgeType)
+ return false;
+ if (properties == null) {
+ if (other.properties != null)
+ return false;
+ } else if (!properties.equals(other.properties))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "GraphEdge [edgeType=" + edgeType + ", properties=" + properties + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphElement.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphElement.java
new file mode 100644
index 0000000000..660e28c674
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphElement.java
@@ -0,0 +1,58 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.graph.datatype;
+
+import java.util.Map;
+
+public abstract class GraphElement {
+
+ private GraphElementTypeEnum elementType;
+ private ActionEnum action;
+
+ protected GraphElement(GraphElementTypeEnum elementType) {
+ this.elementType = elementType;
+ this.action = ActionEnum.NoAction;
+ }
+
+ public GraphElementTypeEnum getElementType() {
+ return elementType;
+ }
+
+ public ActionEnum getAction() {
+ return action;
+ }
+
+ public void setAction(ActionEnum action) {
+ this.action = action;
+ }
+
+ public void setElementType(GraphElementTypeEnum elementType) {
+ this.elementType = elementType;
+ }
+
+ public abstract Map<String, Object> toGraphMap();
+
+ @Override
+ public String toString() {
+ return "GraphElement [elementType=" + elementType + ", action=" + action + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphElementTypeEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphElementTypeEnum.java
new file mode 100644
index 0000000000..0d39b3e39e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphElementTypeEnum.java
@@ -0,0 +1,25 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.graph.datatype;
+
+public enum GraphElementTypeEnum {
+ Node, Relationship
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java
new file mode 100644
index 0000000000..5da11cb738
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java
@@ -0,0 +1,77 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.graph.datatype;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.Gson;
+
+public abstract class GraphNode extends GraphElement {
+
+ private static final Gson gson = new Gson();
+
+ private NodeTypeEnum label;
+
+ protected Gson getGson() {
+ return gson;
+ }
+
+ protected GraphNode(NodeTypeEnum label) {
+ super(GraphElementTypeEnum.Node);
+
+ this.label = label;
+ }
+
+ public String getLabel() {
+ return label.getName();
+ }
+
+ public ImmutablePair<String, Object> getKeyValueId() {
+ ImmutablePair<String, Object> keyValue = new ImmutablePair<String, Object>(getUniqueIdKey(), getUniqueId());
+ return keyValue;
+ }
+
+ protected void addIfExists(Map<String, Object> map, GraphPropertiesDictionary property, Object value) {
+ if (value != null) {
+ if (value instanceof List || value instanceof Map) {
+ value = getGson().toJson(value);
+ }
+ map.put(property.getProperty(), value);
+ }
+ }
+
+ public String getUniqueIdKey() {
+ return GraphPropertiesDictionary.UNIQUE_ID.getProperty();
+ }
+
+ public abstract Object getUniqueId();
+
+ @Override
+ public String toString() {
+ return "GraphNode [label=" + label + ", parent: " + super.toString() + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java
new file mode 100644
index 0000000000..4dfd1544d4
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java
@@ -0,0 +1,106 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.graph.datatype;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class GraphRelation extends GraphElement {
+
+ private RelationEndPoint from;
+ private RelationEndPoint to;
+ private String type;
+ private Map<String, Object> properties;
+
+ public GraphRelation() {
+ super(GraphElementTypeEnum.Relationship);
+ properties = new HashMap<String, Object>();
+ }
+
+ public GraphRelation(String type) {
+ super(GraphElementTypeEnum.Relationship);
+ properties = new HashMap<String, Object>();
+ setType(type);
+ }
+
+ public RelationEndPoint getFrom() {
+ return from;
+ }
+
+ public void setFrom(RelationEndPoint from) {
+ this.from = from;
+ }
+
+ public RelationEndPoint getTo() {
+ return to;
+ }
+
+ public void setTo(RelationEndPoint to) {
+ this.to = to;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public void addProperty(String property, Object value) {
+ if (property != null && !property.isEmpty() && value != null) {
+ properties.put(property, value);
+ }
+ }
+
+ public void addPropertis(Map<String, Object> props) {
+ properties.putAll(props);
+ }
+
+ public void overwritePropertis(Map<String, Object> props) {
+ properties = props;
+ }
+
+ public Object getProperty(String property) {
+ return properties.get(property);
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ return properties;
+ }
+
+ @Override
+ public String toString() {
+ return "GraphRelation [from=" + from + ", to=" + to + ", type=" + type + ", properties=" + properties + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((from == null) ? 0 : from.hashCode());
+ result = prime * result + ((properties == null) ? 0 : properties.hashCode());
+ result = prime * result + ((to == null) ? 0 : to.hashCode());
+ result = prime * result + ((type == null) ? 0 : type.hashCode());
+ return result;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/RelationEndPoint.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/RelationEndPoint.java
new file mode 100644
index 0000000000..9d72717b8e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/RelationEndPoint.java
@@ -0,0 +1,100 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.graph.datatype;
+
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class RelationEndPoint {
+ NodeTypeEnum label;
+ String idName;
+ Object idValue;
+
+ public RelationEndPoint(NodeTypeEnum label, String idName, Object idValue) {
+ super();
+ this.label = label;
+ this.idName = idName;
+ this.idValue = idValue;
+ }
+
+ public NodeTypeEnum getLabel() {
+ return label;
+ }
+
+ public void setLabel(NodeTypeEnum label) {
+ this.label = label;
+ }
+
+ public String getIdName() {
+ return idName;
+ }
+
+ public void setIdName(String idName) {
+ this.idName = idName;
+ }
+
+ public Object getIdValue() {
+ return idValue;
+ }
+
+ public void setIdValue(Object idValue) {
+ this.idValue = idValue;
+ }
+
+ @Override
+ public String toString() {
+ return "RelationEndPoint [label=" + label + ", idName=" + idName + ", idValue=" + idValue + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((idName == null) ? 0 : idName.hashCode());
+ result = prime * result + ((idValue == null) ? 0 : idValue.hashCode());
+ result = prime * result + ((label == null) ? 0 : label.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ RelationEndPoint other = (RelationEndPoint) obj;
+ if (idName == null) {
+ if (other.idName != null)
+ return false;
+ } else if (!idName.equals(other.idName))
+ return false;
+ if (idValue == null) {
+ if (other.idValue != null)
+ return false;
+ } else if (!idValue.equals(other.idValue))
+ return false;
+ if (label != other.label)
+ return false;
+ return true;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java
new file mode 100644
index 0000000000..2cf479ec64
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java
@@ -0,0 +1,264 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.impl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.annotation.PostConstruct;
+
+import org.elasticsearch.index.query.BoolQueryBuilder;
+import org.elasticsearch.index.query.QueryBuilder;
+import org.elasticsearch.index.query.QueryBuilders;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
+import org.openecomp.sdc.common.config.EcompErrorName;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import fj.data.Either;
+
+@Component("auditingDao")
+public class AuditingDao extends ESTimeBasedDao {
+
+ private static final String SERVICE_INSTANCE_ID_FIELD = AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID
+ .getDisplayName(); // "serviceInstanceId";
+ private static final String STATUS_FIELD = AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(); // "status";
+ private static final String ACTION_FIELD = AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(); // "action";
+ private static final String DISTRIBUTION_ID_FIELD = AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(); // "distributionId";
+ private static Logger log = LoggerFactory.getLogger(AuditingDao.class.getName());
+ public static final String AUDITING_INDEX = "auditingevents";
+
+ @PostConstruct
+ private void init() {
+ AuditingActionEnum[] values = AuditingActionEnum.values();
+ for (AuditingActionEnum value : values) {
+ typesToClasses.put(value.getAuditingEsType(), ESTimeBasedEvent.class);
+ }
+ }
+
+ @Override
+ public String getIndexPrefix() {
+ return AUDITING_INDEX;
+ }
+
+ public ActionStatus addRecord(Map<AuditingFieldsKeysEnum, Object> params, String type) {
+
+ // TODO rhalili - remove? check debugEnabled?
+ Map<String, Object> displayFields = new HashMap<String, Object>();
+ StringBuilder sb = new StringBuilder();
+ for (Entry<AuditingFieldsKeysEnum, Object> entry : params.entrySet()) {
+ displayFields.put(entry.getKey().getDisplayName(), entry.getValue());
+ sb.append(entry.getKey().getDisplayName()).append(" = ").append(entry.getValue()).append(",");
+ }
+
+ // Persisiting
+ // String type = clazz.getSimpleName().toLowerCase();
+ AuditingGenericEvent auditingGenericEvent = new AuditingGenericEvent();
+ populateCommonFields(params, auditingGenericEvent);
+ auditingGenericEvent.getFields().putAll(displayFields);
+
+ log.debug("Auditing: Persisting object of type {}, fields: {}", type, sb.toString());
+
+ return write(type, auditingGenericEvent);
+ }
+
+ public Either<List<ESTimeBasedEvent>, ActionStatus> getListOfDistributionStatuses(String did) {
+
+ QueryBuilder componentNameMatch = QueryBuilders.matchQuery(DISTRIBUTION_ID_FIELD, did);
+ QueryBuilder componentVersionMatch = QueryBuilders.matchQuery(ACTION_FIELD,
+ AuditingActionEnum.DISTRIBUTION_STATUS.getName());
+ QueryBuilder remainingElementQueryBuilder = QueryBuilders.boolQuery().must(componentNameMatch)
+ .must(componentVersionMatch);
+ List<ESTimeBasedEvent> remainingElements = null;
+ try {
+ remainingElements = customFindEvent(AuditingTypesConstants.DISTRIBUTION_STATUS_EVENT_TYPE,
+ remainingElementQueryBuilder, null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Get DistributionStatuses List");
+
+ log.debug("failed to get distribution statuses for ", e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ if (remainingElements != null && !remainingElements.isEmpty()) {
+ return Either.left(remainingElements);
+ } else {
+ log.debug("not found distribution statuses for did {}", did);
+ remainingElements = new ArrayList<ESTimeBasedEvent>();
+ return Either.left(remainingElements);
+ }
+
+ }
+
+ public Either<List<ESTimeBasedEvent>, ActionStatus> getServiceDistributionStatusesList(String serviceInstanceId) {
+
+ List<ESTimeBasedEvent> resList = new ArrayList<ESTimeBasedEvent>();
+ QueryBuilder componentNameMatch = QueryBuilders.matchQuery(SERVICE_INSTANCE_ID_FIELD, serviceInstanceId);
+ QueryBuilder componentVersionMatch = QueryBuilders.matchQuery(ACTION_FIELD,
+ AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName());
+ QueryBuilder remainingElementQueryBuilder = QueryBuilders.boolQuery().must(componentNameMatch)
+ .must(componentVersionMatch);
+ List<ESTimeBasedEvent> remainingElements = null;
+ try {
+ remainingElements = customFindEvent(AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE,
+ remainingElementQueryBuilder, null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get Service DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
+ log.debug("failed to get distribution statuses for action {}",
+ AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ if (remainingElements != null && !remainingElements.isEmpty()) {
+ resList.addAll(remainingElements);
+ }
+
+ componentVersionMatch = QueryBuilders.matchQuery(ACTION_FIELD,
+ AuditingActionEnum.DISTRIBUTION_DEPLOY.getName());
+ remainingElementQueryBuilder = QueryBuilders.boolQuery().must(componentNameMatch).must(componentVersionMatch);
+ List<ESTimeBasedEvent> dResultElements = null;
+ try {
+ dResultElements = customFindEvent(AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE,
+ remainingElementQueryBuilder, null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get Service DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
+ log.debug("failed to get distribution statuses for action {}",
+ AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ if (dResultElements != null && !dResultElements.isEmpty()) {
+ resList.addAll(dResultElements);
+ }
+
+ componentVersionMatch = QueryBuilders.matchQuery(ACTION_FIELD,
+ AuditingActionEnum.DISTRIBUTION_NOTIFY.getName());
+ remainingElementQueryBuilder = QueryBuilders.boolQuery().must(componentNameMatch).must(componentVersionMatch);
+ List<ESTimeBasedEvent> dNotifyElements = null;
+ try {
+ dNotifyElements = customFindEvent(AuditingTypesConstants.DISTRIBUTION_NOTIFICATION_EVENT_TYPE,
+ remainingElementQueryBuilder, null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get Service DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
+ log.debug("failed to get distribution statuses for action {}",
+ AuditingActionEnum.DISTRIBUTION_NOTIFY.getName(), e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+ if (remainingElements != null && !remainingElements.isEmpty()) {
+ resList.addAll(dNotifyElements);
+ }
+
+ return Either.left(resList);
+
+ }
+
+ public Either<List<ESTimeBasedEvent>, ActionStatus> getFilteredResourceAdminAuditingEvents(
+ Map<AuditingFieldsKeysEnum, Object> filterMap) {
+
+ Iterator<Entry<AuditingFieldsKeysEnum, Object>> filterItr = filterMap.entrySet().iterator();
+ BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
+ while (filterItr.hasNext()) {
+ Entry<AuditingFieldsKeysEnum, Object> curr = filterItr.next();
+ boolQuery = boolQuery.must(QueryBuilders.termQuery(curr.getKey().getDisplayName(), curr.getValue()));
+ }
+
+ try {
+ List<ESTimeBasedEvent> customFindEvent = customFindEvent(
+ ResourceAdminEvent.class.getSimpleName().toLowerCase(), boolQuery, null);
+ return Either.left(customFindEvent);
+ } catch (Exception e) {
+ log.debug("Failed to query AuditRecords in es");
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+
+ }
+
+ public Either<List<ESTimeBasedEvent>, ActionStatus> getListOfDistributionByAction(String did, String actionType,
+ String requestedStatus, Class<? extends AuditingGenericEvent> clazz) {
+
+ QueryBuilder distributionIdMatch = QueryBuilders.matchQuery(DISTRIBUTION_ID_FIELD, did);
+ QueryBuilder distributionActionMatch = QueryBuilders.matchQuery(ACTION_FIELD, actionType);
+ QueryBuilder remainingElementQueryBuilder;
+
+ if (requestedStatus != null && !requestedStatus.isEmpty()) {
+ QueryBuilder statusMatch = QueryBuilders.matchQuery(STATUS_FIELD, requestedStatus);
+ remainingElementQueryBuilder = QueryBuilders.boolQuery().must(distributionIdMatch)
+ .must(distributionActionMatch).must(statusMatch);
+ } else {
+ remainingElementQueryBuilder = QueryBuilders.boolQuery().must(distributionIdMatch)
+ .must(distributionActionMatch);
+ }
+
+ List<ESTimeBasedEvent> remainingElements = null;
+ try {
+ remainingElements = customFindEvent(clazz.getSimpleName().toLowerCase(), remainingElementQueryBuilder,
+ null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get DistributionStatuses List");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Get DistributionStatuses List");
+ log.debug("failed to get distribution statuses for action {}", actionType, e);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+
+ return Either.left(remainingElements);
+
+ }
+
+ private void populateCommonFields(Map<AuditingFieldsKeysEnum, Object> params,
+ AuditingGenericEvent timeBasedIndexedData) {
+ String dateStr = (String) params.get(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP);
+ if (dateStr != null) {
+ timeBasedIndexedData.setTimestamp(dateStr);
+ }
+ timeBasedIndexedData.setAction((String) params.get(AuditingFieldsKeysEnum.AUDIT_ACTION));
+ Object statusObj = params.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ // For BC. status was Integer and is String
+ if (statusObj != null) {
+ timeBasedIndexedData.setStatus(String.valueOf(statusObj));
+ } else {
+ timeBasedIndexedData.setStatus(null);
+ }
+ // timeBasedIndexedData.setStatus((String)params.get(AuditingFieldsKeysEnum.AUDIT_STATUS));
+ timeBasedIndexedData.setDesc((String) params.get(AuditingFieldsKeysEnum.AUDIT_DESC));
+ timeBasedIndexedData
+ .setServiceInstanceId((String) params.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID));
+ timeBasedIndexedData.setRequestId((String) params.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID));
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java
new file mode 100644
index 0000000000..87cd8a5f3e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java
@@ -0,0 +1,214 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.impl;
+
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+
+import javax.annotation.PostConstruct;
+
+import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
+import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
+import org.elasticsearch.common.unit.TimeValue;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ESGenericSearchDAO;
+import org.openecomp.sdc.be.dao.api.ICatalogDAO;
+import org.openecomp.sdc.be.dao.api.ResourceUploadStatus;
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.be.resources.exception.ResourceDAOException;
+import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
+import org.openecomp.sdc.common.config.EcompErrorName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+
+import fj.data.Either;
+
+@Component("resource-dao")
+public class ESCatalogDAO extends ESGenericSearchDAO implements ICatalogDAO {
+
+ private static Logger log = LoggerFactory.getLogger(ESCatalogDAO.class.getName());
+ private static Logger healthCheckLogger = LoggerFactory.getLogger("elasticsearch.healthcheck");
+
+ ///// HealthCheck/////////
+ private static final String ES_HEALTH_CHECK_STR = "elasticsearchHealthCheck";
+
+ private ScheduledExecutorService healthCheckScheduler = Executors
+ .newSingleThreadScheduledExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable r) {
+ return new Thread(r, "ES-Health-Check-Thread");
+ }
+ });
+
+ private class HealthCheckScheduledTask implements Runnable {
+ @Override
+ public void run() {
+ healthCheckLogger.trace("Executing ELASTICSEARCH Health Check Task - Start");
+
+ HealthCheckStatus healthStatus = null;
+ try {
+ healthStatus = isInitCompleted() ? checkHealth() : HealthCheckStatus.DOWN;
+ } catch (Exception e) {
+ log.error("Error while trying to connect to elasticsearch. host: " + getEsClient().getServerHost()
+ + " port: " + getEsClient().getServerPort(), e.getMessage());
+ log.trace("Error while trying to connect to elasticsearch", e);
+ healthStatus = HealthCheckStatus.DOWN;
+ }
+ healthCheckLogger.trace("Executed ELASTICSEARCH Health Check Task - Status = {}", healthStatus);
+ if (healthStatus != lastHealthState) {
+ log.trace("ELASTICSEARCH Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
+ lastHealthState = healthStatus;
+ logAlarm();
+ }
+ }
+ }
+
+ private HealthCheckScheduledTask healthCheckScheduledTask = new HealthCheckScheduledTask();
+ private volatile HealthCheckStatus lastHealthState = HealthCheckStatus.DOWN;
+
+ /**
+ * Get ES cluster status string rep
+ *
+ * @return "GREEN", "YELLOW" or "RED"
+ */
+ private HealthCheckStatus checkHealth() {
+ if (!isInitCompleted()) {
+ return HealthCheckStatus.DOWN;
+ }
+ ClusterHealthRequest healthRequest = new ClusterHealthRequest("_all");
+ healthRequest.masterNodeTimeout(TimeValue.timeValueSeconds(2));
+ ClusterHealthStatus status = getClient().admin().cluster().health(healthRequest).actionGet().getStatus();
+ healthCheckLogger.debug("ES cluster health status is {}", status);
+ if (status == null || status.equals(ClusterHealthStatus.RED)) {
+ return HealthCheckStatus.DOWN;
+ }
+ return HealthCheckStatus.UP;
+ }
+
+ private void logAlarm() {
+ if (lastHealthState == HealthCheckStatus.UP) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckRecovery,
+ ES_HEALTH_CHECK_STR);
+ BeEcompErrorManager.getInstance().logBeHealthCheckElasticSearchRecovery(ES_HEALTH_CHECK_STR);
+ } else {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckError, ES_HEALTH_CHECK_STR);
+ BeEcompErrorManager.getInstance().logBeHealthCheckElasticSearchError(ES_HEALTH_CHECK_STR);
+ }
+ }
+
+ @PostConstruct
+ public void initCompleted() {
+ long interval = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getEsReconnectIntervalInSeconds(5);
+ this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, interval, TimeUnit.SECONDS);
+ initCompleted = true;
+ }
+
+ // Index Checking Variables
+ private boolean initCompleted = false;
+
+ @Override
+ public void writeArtifact(ESArtifactData artifactData) throws ResourceDAOException {
+ try {
+ saveResourceData(artifactData);
+ } catch (Exception e) {
+ throw new ResourceDAOException("Error to save ArtifactData with " + artifactData.getId());
+ }
+ }
+
+ @Override
+ public Either<ESArtifactData, ResourceUploadStatus> getArtifact(String id) {
+ ESArtifactData resData = null;
+
+ try {
+ resData = findById(getTypeFromClass(ESArtifactData.class), id, ESArtifactData.class);
+ } catch (Exception e) {
+ resData = null;
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Get Artifact from database");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Artifact from database");
+ log.debug("ESCatalogDAO:getArtifact failed with exception ", e);
+ return Either.right(ResourceUploadStatus.ERROR);
+ }
+
+ if (resData != null) {
+ return Either.left(resData);
+ } else {
+ return Either.right(ResourceUploadStatus.NOT_EXIST);
+ }
+ }
+
+ private <T> String getTypeFromClass(Class<T> clazz) {
+
+ return clazz.getSimpleName().toLowerCase();
+ }
+
+ @Override
+ public void deleteArtifact(String id) {
+ delete(getTypeFromClass(ESArtifactData.class), id);
+ }
+
+ @Override
+ public Either<List<ESArtifactData>, ResourceUploadStatus> getArtifacts(String[] ids) {
+ List<ESArtifactData> resData = null;
+ try {
+ resData = findByIds(getTypeFromClass(ESArtifactData.class), ESArtifactData.class, ids);
+ } catch (Exception e) {
+ resData = null;
+ return Either.right(ResourceUploadStatus.ERROR);
+ }
+
+ if (resData != null && !resData.isEmpty()) {
+ return Either.left(resData);
+ } else {
+ return Either.right(ResourceUploadStatus.NOT_EXIST);
+ }
+ }
+
+ private void saveResourceData(ESArtifactData data) throws JsonProcessingException {
+ String typeName = getTypeFromClass(data.getClass());
+ saveResourceData(typeName, data, data.getId());
+ }
+
+ @Override
+ public void deleteAllArtifacts() {
+ String typeName = getTypeFromClass(ESArtifactData.class);
+ String indexName = getIndexForType(typeName);
+ deleteIndex(indexName);
+
+ }
+
+ public boolean isInitCompleted() {
+ return initCompleted;
+ }
+
+ public HealthCheckStatus getHealth() {
+ return lastHealthState;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java
new file mode 100644
index 0000000000..b7666392aa
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java
@@ -0,0 +1,305 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.impl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.Resource;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.elasticsearch.action.index.IndexResponse;
+import org.elasticsearch.action.search.SearchRequestBuilder;
+import org.elasticsearch.action.search.SearchResponse;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.index.query.QueryBuilder;
+import org.elasticsearch.search.sort.SortBuilder;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig.IndicesTimeFrequencyEntry;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public abstract class ESTimeBasedDao {
+ private static final String SCORE_SCRIPT = "_score * ((doc.containsKey('alienScore') && !doc['alienScore'].empty) ? doc['alienScore'].value : 1)";
+ private static final int MAX_SEARCH_SIZE = 1000;
+ private static Logger log = LoggerFactory.getLogger(ESTimeBasedDao.class.getName());
+
+ private Gson gson;
+
+ private Map<String, String> indexPrefix2CreationPeriod;
+
+ private ConfigurationManager configurationManager;
+
+ protected ESTimeBasedDao() {
+ gson = new GsonBuilder().setPrettyPrinting().create();
+ configurationManager = ConfigurationManager.getConfigurationManager();
+ setIndexPrefix2CreationPeriod();
+ }
+
+ public void setConfigurationManager(ConfigurationManager configurationManager) {
+ this.configurationManager = configurationManager;
+ }
+
+ @Resource(name = "elasticsearch-client")
+ private ElasticSearchClient esClient;
+
+ protected final Map<String, Class<?>> typesToClasses = new HashMap<String, Class<?>>();
+
+ public abstract String getIndexPrefix();
+
+ public ActionStatus write(String typeName, ESTimeBasedEvent data) {
+
+ String indexPrefix = getIndexPrefix();
+ String indexSuffix = getIndexSuffix(indexPrefix, data);
+ StringBuilder sb = new StringBuilder();
+ sb.append(indexPrefix);
+ if (indexSuffix != null) {
+ sb.append("-").append(indexSuffix);
+ }
+
+ ActionStatus res = ActionStatus.OK;
+ JSONObject json = new JSONObject(data.getFields());
+ try {
+ IndexResponse actionGet = esClient.getClient().prepareIndex(sb.toString(), typeName)
+ .setSource(json.toString()).setRefresh(true).execute().actionGet(TimeValue.timeValueSeconds(15));
+
+ if (actionGet.isCreated()) {
+ log.debug("Created record {}", data.toString());
+ // typesToClasses.put(typeName, data.getClass());
+ } else {
+ log.error("Record {} couldn't be created", data.toString());
+ res = ActionStatus.GENERAL_ERROR;
+ }
+ } catch (Exception e) {
+ log.error("Couldn't serialize object of type " + typeName + " , error:", e);
+ res = ActionStatus.GENERAL_ERROR;
+ }
+ return res;
+ }
+
+ public ActionStatus write(ESTimeBasedEvent data) {
+
+ String indexPrefix = getIndexPrefix();
+ String indexSuffix = getIndexSuffix(indexPrefix, data);
+ StringBuilder sb = new StringBuilder();
+ sb.append(indexPrefix);
+ if (indexSuffix != null) {
+ sb.append("-").append(indexSuffix);
+ }
+
+ String typeName = data.getClass().getSimpleName().toLowerCase();
+ ActionStatus res = ActionStatus.OK;
+ String json = gson.toJson(data);
+ try {
+ IndexResponse actionGet = esClient.getClient().prepareIndex(sb.toString(), typeName).setSource(json)
+ .setRefresh(true).execute().actionGet(TimeValue.timeValueSeconds(15));
+
+ if (actionGet.isCreated()) {
+ log.debug("Created record {}", data.toString());
+ // typesToClasses.put(typeName, data.getClass());
+ } else {
+ log.error("Record {} couldn't be created", data.toString());
+ res = ActionStatus.GENERAL_ERROR;
+ }
+ } catch (Exception e) {
+ log.debug("Couldn't serialize object of type {}", typeName);
+ res = ActionStatus.GENERAL_ERROR;
+ }
+ return res;
+ }
+
+ private void setIndexPrefix2CreationPeriod() {
+ indexPrefix2CreationPeriod = new HashMap<String, String>();
+ List<IndicesTimeFrequencyEntry> indicesTimeFrequencyEntries = configurationManager.getConfiguration()
+ .getElasticSearch().getIndicesTimeFrequency();
+ for (IndicesTimeFrequencyEntry entry : indicesTimeFrequencyEntries) {
+ indexPrefix2CreationPeriod.put(entry.getIndexPrefix(), entry.getCreationPeriod());
+
+ }
+ }
+
+ private String getIndexSuffix(String indexPrefix, ESTimeBasedEvent data) {
+ String indexSuffix = indexPrefix2CreationPeriod.get(indexPrefix);
+ String res = null;
+ if (indexSuffix != null) {
+ if (indexSuffix.equalsIgnoreCase(Constants.YEAR)) {
+ res = data.calculateYearIndexSuffix();
+ } else if (indexSuffix.equalsIgnoreCase(Constants.MONTH)) {
+ res = data.calculateMonthIndexSuffix();
+ } else if (indexSuffix.equalsIgnoreCase(Constants.DAY)) {
+ res = data.calculateDayIndexSuffix();
+ } else if (indexSuffix.equalsIgnoreCase(Constants.HOUR)) {
+ res = data.calculateHourIndexSuffix();
+ } else if (indexSuffix.equalsIgnoreCase(Constants.MINUTE)) {
+ res = data.calculateMinuteIndexSuffix();
+ } else if (indexSuffix.equalsIgnoreCase(Constants.NONE)) {
+ // do nothing - no time-based behaviour. I wanted to ensure
+ // proper syntax, that's why this clause is needed.
+ }
+ } else {
+ // Default behaviour - time-based with month period
+ res = data.calculateMonthIndexSuffix();
+ }
+ return res;
+ }
+
+ public <T> long count(Class<T> clazz, QueryBuilder query) {
+ String indexName = getIndexPrefix() + "*";
+ String typeName = clazz.getSimpleName().toLowerCase();
+ SearchRequestBuilder searchRequestBuilder = esClient.getClient().prepareSearch(indexName).setTypes(typeName)
+ .setSize(0);
+ if (query != null) {
+ searchRequestBuilder.setQuery(query);
+ }
+
+ SearchResponse response = searchRequestBuilder.execute().actionGet();
+ return response.getHits().getTotalHits();
+ }
+
+ private <T> List<T> doCustomFind(Class<T> clazz, QueryBuilder query, SortBuilder sortBuilder, int size) {
+ String indexName = getIndexPrefix() + "*";
+ String typeName = clazz.getSimpleName().toLowerCase();
+ SearchRequestBuilder searchRequestBuilder = esClient.getClient().prepareSearch(indexName).setTypes(typeName)
+ .setSize(size);
+ if (query != null) {
+ searchRequestBuilder.setQuery(query);
+ }
+ if (sortBuilder != null) {
+ searchRequestBuilder.addSort(sortBuilder);
+ }
+ SearchResponse response = searchRequestBuilder.execute().actionGet();
+ if (!somethingFound(response)) {
+ return null;
+ } else {
+ List<T> hits = new ArrayList<T>();
+ for (int i = 0; i < response.getHits().getHits().length; i++) {
+ String hit = response.getHits().getAt(i).sourceAsString();
+
+ hits.add((T) gson.fromJson(hit, clazz));
+
+ }
+ return hits;
+ }
+ }
+
+ private List<ESTimeBasedEvent> doCustomFindForEvent(String typeName, QueryBuilder query, SortBuilder sortBuilder,
+ int size) {
+ String indexName = getIndexPrefix() + "*";
+ // String typeName = clazz.getSimpleName().toLowerCase();
+ SearchRequestBuilder searchRequestBuilder = esClient.getClient().prepareSearch(indexName).setTypes(typeName)
+ .setSize(size);
+ if (query != null) {
+ searchRequestBuilder.setQuery(query);
+ }
+ if (sortBuilder != null) {
+ searchRequestBuilder.addSort(sortBuilder);
+ }
+ SearchResponse response = searchRequestBuilder.execute().actionGet();
+ if (!somethingFound(response)) {
+ return null;
+ } else {
+ List<ESTimeBasedEvent> hits = new ArrayList<ESTimeBasedEvent>();
+ for (int i = 0; i < response.getHits().getHits().length; i++) {
+ String hit = response.getHits().getAt(i).sourceAsString();
+
+ ESTimeBasedEvent event;
+ try {
+ event = ESTimeBasedEvent.createEventFromJson(hit);
+ hits.add(event);
+ } catch (JSONException e) {
+ log.warn("failed to parse hit from audit index. error: {}", e.getMessage());
+ log.debug("failed to parse hit from audit. hit = {} {}", hit, e);
+ }
+ }
+ return hits;
+ }
+ }
+
+ public List<ESTimeBasedEvent> customFindEvent(String typeName, QueryBuilder query, SortBuilder sortBuilder)
+ throws JSONException {
+ List<ESTimeBasedEvent> results = doCustomFindForEvent(typeName, query, sortBuilder, MAX_SEARCH_SIZE);
+ if (results == null) {
+ results = new ArrayList<ESTimeBasedEvent>();
+ }
+ return results;
+ }
+
+ public <T> T customFind(Class<T> clazz, QueryBuilder query) {
+ return customFind(clazz, query, null);
+ }
+
+ public <T> T customFind(Class<T> clazz, QueryBuilder query, SortBuilder sortBuilder) {
+ List<T> results = doCustomFind(clazz, query, sortBuilder, 1);
+ if (results == null || results.isEmpty()) {
+ return null;
+ } else {
+ return results.iterator().next();
+ }
+ }
+
+ public <T> List<T> customFindAll(Class<T> clazz, QueryBuilder query) {
+ return customFindAll(clazz, query, null);
+ }
+
+ public <T> List<T> customFindAll(Class<T> clazz, QueryBuilder query, SortBuilder sortBuilder) {
+ return doCustomFind(clazz, query, sortBuilder, Integer.MAX_VALUE);
+ }
+
+ private boolean somethingFound(final SearchResponse searchResponse) {
+ if (searchResponse == null || searchResponse.getHits() == null || searchResponse.getHits().getHits() == null
+ || searchResponse.getHits().getHits().length == 0) {
+ return false;
+ }
+ return true;
+ }
+
+ public String getEsHost() {
+ String host = null;
+ if (this.esClient != null) {
+ host = this.esClient.getServerHost();
+ } else {
+ log.error("esClient is unavilable could not get host.");
+ }
+ return host;
+ }
+
+ public String getEsPort() {
+ String port = null;
+ if (this.esClient != null) {
+ port = this.esClient.getServerPort();
+ } else {
+ log.error("esClient is unavilable could not get port.");
+ }
+
+ return port;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java
new file mode 100644
index 0000000000..04d985bc83
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java
@@ -0,0 +1,50 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.impl;
+
+import javax.annotation.Resource;
+
+import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao;
+import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
+import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+@Component("esHealthCheckDao")
+public class EsHealthCheckDao implements IEsHealthCheckDao {
+
+ private static Logger logger = LoggerFactory.getLogger(EsHealthCheckDao.class.getName());
+
+ @Resource(name = "elasticsearch-client")
+ private ElasticSearchClient esClient;
+
+ @Resource
+ private ESCatalogDAO esCatalogDao;
+
+ public EsHealthCheckDao() {
+ }
+
+ public HealthCheckStatus getClusterHealthStatus() {
+ return this.esCatalogDao.getHealth();
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/MonitoringDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/MonitoringDao.java
new file mode 100644
index 0000000000..1c16c155a5
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/MonitoringDao.java
@@ -0,0 +1,41 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.impl;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.common.monitoring.MonitoringEvent;
+import org.springframework.stereotype.Component;
+
+@Component("monitoringDao")
+public class MonitoringDao extends ESTimeBasedDao {
+
+ public static final String MONITORING_INDEX = "monitoring_events";
+
+ @Override
+ public String getIndexPrefix() {
+ return MONITORING_INDEX;
+ }
+
+ public ActionStatus addRecord(MonitoringEvent monitoringEvent) {
+ return write(monitoringEvent);
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jElementDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jElementDAO.java
new file mode 100644
index 0000000000..d6b8d2eed8
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jElementDAO.java
@@ -0,0 +1,112 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.impl;
+
+import java.util.List;
+
+import javax.annotation.Resource;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.api.IElementDAO;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElement;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jClient;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus;
+import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import fj.data.Either;
+
+//@Component("elements-dao")
+public class Neo4jElementDAO implements IElementDAO {
+
+ // @Resource
+ Neo4jClient neo4jClient;
+
+ private static Logger logger = LoggerFactory.getLogger(Neo4jElementDAO.class.getName());
+
+ @Override
+ public Either<List<GraphElement>, ActionStatus> getAllCategories() {
+ MatchFilter filter = new MatchFilter();
+ Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node,
+ NodeTypeEnum.ResourceCategory.getName(), filter);
+ if (status.isRight()) {
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ } else {
+ List<GraphElement> value = status.left().value();
+ if (value == null || value.isEmpty()) {
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ } else {
+ return Either.left(value);
+ }
+ }
+ }
+
+ @Override
+ public Either<List<GraphElement>, ActionStatus> getAllTags() {
+ MatchFilter filter = new MatchFilter();
+ Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node,
+ NodeTypeEnum.Tag.getName(), filter);
+ if (status.isRight()) {
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ } else {
+ List<GraphElement> value = status.left().value();
+ if (value == null) {
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ } else {
+ return Either.left(value);
+ }
+ }
+ }
+
+ @Override
+ public Either<GraphElement, ActionStatus> getCategory(String name) {
+ MatchFilter filter = new MatchFilter();
+ filter.addToMatch(GraphPropertiesDictionary.NAME.getProperty(), name);
+ Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node,
+ NodeTypeEnum.ResourceCategory.getName(), filter);
+ if (status.isRight()) {
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ } else {
+ List<GraphElement> value = status.left().value();
+ if (value == null) {
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ } else {
+ return Either.left(value.get(0));
+ }
+ }
+
+ }
+
+ /**
+ * FOR TEST ONLY
+ *
+ * @param neo4jClient
+ */
+ public void setNeo4jClient(Neo4jClient neo4jClient) {
+ this.neo4jClient = neo4jClient;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java
new file mode 100644
index 0000000000..c3a7c50803
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java
@@ -0,0 +1,99 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.impl;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+
+import org.openecomp.sdc.be.dao.api.BasicDao;
+import org.openecomp.sdc.be.dao.api.IPropertyDAO;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jClient;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jGraphBatchBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+//@Component("neo4j-property-dao")
+public class Neo4jPropertyDAO extends BasicDao implements IPropertyDAO {
+
+ // @Resource
+ Neo4jClient neo4jClient;
+
+ private static Logger logger = LoggerFactory.getLogger(Neo4jPropertyDAO.class.getName());
+
+ Neo4jGraphBatchBuilder graphBatchBuilder = new Neo4jGraphBatchBuilder();
+
+ public Neo4jPropertyDAO() {
+
+ }
+
+ @PostConstruct
+ public void init() {
+ setNeo4jClient(neo4jClient);
+ }
+
+ // @Override
+ // public Either<PropertyData, Neo4jOperationStatus> createPropertyData(
+ // GraphNeighbourTable graphNeighbourTable) {
+ //
+ // Either<BatchBuilder, Neo4jOperationStatus> bbResult = graphBatchBuilder
+ // .buildBatchBuilderFromTable(graphNeighbourTable);
+ //
+ // if (bbResult.isLeft()) {
+ //
+ // BatchBuilder batchBuilder = bbResult.left().value();
+ // //Neo4jOperationStatus neo4jOperationStatus =
+ // neo4jClient.execute(batchBuilder);
+ // Either<List<List<Neo4jElement>>, Neo4jOperationStatus> executeResult =
+ // neo4jClient.execute(batchBuilder);
+ //
+ // if (executeResult.isRight()) {
+ // return Either.right(executeResult.right().value());
+ // }
+ //
+ // PropertyData propertyData = null;
+ // List<List<Neo4jElement>> listOfResults = executeResult.left().value();
+ // if (listOfResults != null) {
+ // for (List<Neo4jElement> listOfElements : listOfResults) {
+ // if (listOfElements != null && false == listOfElements.isEmpty()) {
+ // for (Neo4jElement element : listOfElements) {
+ // logger.debug("element {} was returned after running batch operation {}", element, batchBuilder);
+ // if (element instanceof Neo4jNode) {
+ // Neo4jNode neo4jNode = (Neo4jNode) element;
+ // if (NodeTypeEnum.getByName(neo4jNode.getLabel()) ==
+ // NodeTypeEnum.Property) {
+ // propertyData = (PropertyData)neo4jNode;
+ // }
+ // }
+ // }
+ // }
+ // }
+ // }
+ //
+ // return Either.left(propertyData);
+ //
+ // } else {
+ // return Either.right(bbResult.right().value());
+ // }
+ //
+ // }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java
new file mode 100644
index 0000000000..1647a656f3
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java
@@ -0,0 +1,242 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.impl;
+
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.PostConstruct;
+
+import org.openecomp.sdc.be.dao.api.BasicDao;
+import org.openecomp.sdc.be.dao.api.IResourceDAO;
+import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElement;
+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.graph.datatype.RelationEndPoint;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jClient;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jGraphBatchBuilder;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus;
+import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter;
+import org.openecomp.sdc.be.dao.neo4j.filters.RecursiveFilter;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import fj.data.Either;
+
+//@Component("neo4j-resource-dao")
+public class Neo4jResourceDAO extends BasicDao implements IResourceDAO {
+
+ // @Resource
+ Neo4jClient neo4jClient;
+
+ private static Logger logger = LoggerFactory.getLogger(Neo4jResourceDAO.class.getName());
+
+ Neo4jGraphBatchBuilder graphBatchBuilder = new Neo4jGraphBatchBuilder();
+
+ public Neo4jResourceDAO() {
+
+ }
+
+ @PostConstruct
+ public void init() {
+ super.setNeo4jClient(neo4jClient);
+ }
+
+ // public Either<ResourceData, Neo4jOperationStatus> createResourceData(
+ // GraphNeighbourTable graphNeighbourTable) {
+ //
+ // if (graphNeighbourTable != null) {
+ //
+ // String resourceId = findResourceDataIdFromNodes(graphNeighbourTable
+ // .getNodes());
+ // if (resourceId == null || resourceId.isEmpty()) {
+ // logger.error("Cannot find resource id in the graph table");
+ // return Either.right(Neo4jOperationStatus.BAD_REQUEST);
+ // }
+ //
+ // Either<BatchBuilder, Neo4jOperationStatus> bbResult = graphBatchBuilder
+ // .buildBatchBuilderFromTable(graphNeighbourTable);
+ //
+ // if (bbResult.isLeft()) {
+ //
+ // BatchBuilder batchBuilder = bbResult.left().value();
+ // //Neo4jOperationStatus neo4jOperationStatus =
+ // neo4jClient.execute(batchBuilder);
+ // Either<List<List<Neo4jElement>>, Neo4jOperationStatus> executeResult =
+ // neo4jClient.execute(batchBuilder);
+ //
+ // if (executeResult.isRight()) {
+ // return Either.right(executeResult.right().value());
+ // }
+ //
+ // ResourceData resourceData = null;
+ // List<List<Neo4jElement>> listOfResults = executeResult.left().value();
+ // if (listOfResults != null) {
+ // for (List<Neo4jElement> listOfElements : listOfResults) {
+ // if (listOfElements != null && false == listOfElements.isEmpty()) {
+ // for (Neo4jElement element : listOfElements) {
+ // logger.debug("element {} was returned after running batch operation {}", element, batchBuilder);
+ // if (element instanceof Neo4jNode) {
+ // Neo4jNode neo4jNode = (Neo4jNode) element;
+ // if (NodeTypeEnum.getByName(neo4jNode.getLabel()) ==
+ // NodeTypeEnum.Resource) {
+ // resourceData = (ResourceData)neo4jNode;
+ // }
+ // }
+ // }
+ // }
+ // }
+ // }
+ //
+ // return Either.left(resourceData);
+ //
+ // } else {
+ // return Either.right(bbResult.right().value());
+ // }
+ //
+ // } else {
+ // logger.error("The table sent in order to create resource is empty.");
+ // return Either.right(Neo4jOperationStatus.BAD_REQUEST);
+ // }
+ // }
+
+ private String findResourceDataIdFromNodes(List<GraphNode> nodes) {
+
+ if (nodes != null) {
+
+ for (GraphNode neo4jNode : nodes) {
+ String label = neo4jNode.getLabel();
+ if (label.equals(NodeTypeEnum.Resource.getName())) {
+ return neo4jNode.getUniqueId().toString();
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private GraphRelation addStateRelation(RelationEndPoint from, RelationEndPoint to, GraphEdgeLabels edgeLabel,
+ String value) {
+
+ GraphRelation relationState = new GraphRelation();
+ relationState.setFrom(from);
+ relationState.setTo(to);
+ relationState.setType(edgeLabel.name());
+ relationState.setAction(ActionEnum.Create);
+ return relationState;
+ }
+
+ // private ActionStatus convertNeo4jOperationStatusToActionStatus(
+ // Neo4jOperationStatus value) {
+ //
+ // if (value == null) {
+ // return ActionStatus.GENERAL_ERROR;
+ // }
+ //
+ // switch (value) {
+ // case NOT_FOUND:
+ // return ActionStatus.RESOURCE_NOT_FOUND;
+ // case ERROR:
+ // return ActionStatus.GENERAL_ERROR;
+ // case NOT_SUPPORTED:
+ // return ActionStatus.INVALID_CONTENT;
+ // case WRONG_INPUT:
+ // return ActionStatus.INVALID_CONTENT;
+ // case OK:
+ // return ActionStatus.OK;
+ // default:
+ // return ActionStatus.GENERAL_ERROR;
+ // }
+ //
+ // }
+
+ @Override
+ public Either<ResourceMetadataData, Neo4jOperationStatus> getResourceData(String id) {
+
+ MatchFilter filter = new MatchFilter();
+ filter.addToMatch(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), id);
+ Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node,
+ NodeTypeEnum.Resource.getName(), filter);
+
+ if (status.isRight()) {
+ return Either.right(status.right().value());
+ } else {
+ List<GraphElement> value = status.left().value();
+ if (value == null || value.isEmpty()) {
+ return Either.right(Neo4jOperationStatus.NOT_FOUND);
+ } else {
+ return Either.left((ResourceMetadataData) value.get(0));
+ }
+ }
+ }
+
+ @Override
+ public Either<Integer, Neo4jOperationStatus> getNumberOfResourcesByName(String name) {
+
+ MatchFilter filter = new MatchFilter();
+ filter.addToMatch(GraphPropertiesDictionary.NAME.getProperty(), name);
+ Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node,
+ NodeTypeEnum.Resource.getName(), filter);
+
+ if (status.isRight() || (status.left().value() == null)) {
+ return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
+ } else {
+ List<GraphElement> value = status.left().value();
+ return Either.left(value.size());
+ }
+ }
+
+ @Override
+ public void setNeo4jClient(Neo4jClient client) {
+ this.neo4jClient = client;
+ super.setNeo4jClient(client);
+ }
+
+ @Override
+ public Either<List<ResourceMetadataData>, Neo4jOperationStatus> getAllResourcesData(
+ Map<String, Object> propertiesToMatch) {
+
+ RecursiveFilter filter = new RecursiveFilter(NodeTypeEnum.Resource);
+ // filter.addRelationType("typeof").addRelationType("belong").setProperties(propertiesToMatch);
+
+ Either<List<List<GraphElement>>, Neo4jOperationStatus> ret = neo4jClient.executeGet(filter);
+ if (ret.isRight()) {
+ return Either.right(ret.right().value());
+ }
+ List<List<GraphElement>> listOfListOfNeo4jElement = ret.left().value();
+
+ for (List<GraphElement> row : listOfListOfNeo4jElement) {
+
+ for (GraphElement elem : row) {
+
+ }
+ }
+ return Either.right(null);
+
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java
new file mode 100644
index 0000000000..25a77f1ff1
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java
@@ -0,0 +1,169 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.api.IUsersDAO;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElement;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jClient;
+import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus;
+import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter;
+import org.openecomp.sdc.be.dao.neo4j.filters.UpdateFilter;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.resources.data.UserData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import fj.data.Either;
+
+//@Component("users-dao")
+public class Neo4jUsersDAO implements IUsersDAO {
+
+ // @Resource
+ Neo4jClient neo4jClient;
+
+ private static Logger logger = LoggerFactory.getLogger(Neo4jUsersDAO.class.getName());
+
+ public Neo4jUsersDAO() {
+
+ }
+
+ @PostConstruct
+ public void init() {
+ }
+
+ private void createIndexesAndConstraints() {
+ Either<Map<String, List<String>>, Neo4jOperationStatus> statusInd = neo4jClient
+ .getIndexes(NodeTypeEnum.User.getName());
+ if (statusInd.isRight()) {
+ logger.error("Failed to get indexes from Neo4j graph");
+ throw new RuntimeException("Failed to initialize Neo4jUsersDAO - Failed to get indexes from Neo4j graph");
+ }
+ Map<String, List<String>> indexes = statusInd.left().value();
+ if (indexes == null || indexes.isEmpty()) {
+ logger.info("Define users indexes in Neo4j");
+ List<String> propertyNames = new ArrayList<String>();
+ propertyNames.add("firstName");
+ propertyNames.add("lastName");
+ propertyNames.add("email");
+ propertyNames.add("role");
+ logger.info("Start create Users indexes in Neo4jGraph");
+ Neo4jOperationStatus createIndexStatus = neo4jClient.createIndex(NodeTypeEnum.User.getName(),
+ propertyNames);
+ if (createIndexStatus.equals(Neo4jOperationStatus.OK)) {
+ logger.info("Users indexes created in Neo4j");
+ List<String> propertyUnique = new ArrayList<String>();
+ propertyUnique.add("userId");
+
+ logger.info("Start create Users constraints in Neo4jGraph");
+ Neo4jOperationStatus createUniquenessStatus = neo4jClient
+ .createUniquenessConstraints(NodeTypeEnum.User.getName(), propertyUnique);
+ if (createUniquenessStatus.equals(Neo4jOperationStatus.OK)) {
+ logger.info("Users constraints creatyed in Neo4j");
+ } else {
+ logger.error("Failed to create constraints in Neo4j graph [" + createUniquenessStatus + "]");
+ throw new RuntimeException(
+ "Failed to initialize Neo4jUsersDAO - Failed to create constraints in Neo4j graph");
+ }
+ } else {
+ logger.error("Failed to create indexes in Neo4j graph [" + createIndexStatus + "]");
+ throw new RuntimeException(
+ "Failed to initialize Neo4jUsersDAO - Failed to create indexes in Neo4j graph");
+ }
+ } else {
+ logger.info("Users indexes already defined in Neo4j");
+ }
+ }
+
+ @Override
+ public Either<UserData, ActionStatus> getUserData(String id) {
+ MatchFilter filter = new MatchFilter();
+ filter.addToMatch("userId", id);
+ Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node,
+ NodeTypeEnum.User.getName(), filter);
+ if (status.isRight()) {
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ } else {
+ List<GraphElement> value = status.left().value();
+ if (value == null || value.isEmpty()) {
+ return Either.right(ActionStatus.USER_NOT_FOUND);
+ } else {
+ return Either.left((UserData) value.get(0));
+ }
+ }
+ }
+
+ @Override
+ public ActionStatus saveUserData(UserData userData) {
+ Neo4jOperationStatus status = neo4jClient.createElement(userData);
+ if (status.equals(Neo4jOperationStatus.OK)) {
+ return ActionStatus.OK;
+ } else {
+ return ActionStatus.GENERAL_ERROR;
+ }
+ }
+
+ @Override
+ public ActionStatus updateUserData(UserData userData) {
+ UpdateFilter filter = new UpdateFilter();
+ filter.addToMatch("userId", userData.getUserId());
+ filter.setToUpdate(userData.toGraphMap());
+ Neo4jOperationStatus status = neo4jClient.updateElement(GraphElementTypeEnum.Node, NodeTypeEnum.User.getName(),
+ filter);
+ if (status.equals(Neo4jOperationStatus.OK)) {
+ return ActionStatus.OK;
+ } else {
+ return ActionStatus.GENERAL_ERROR;
+ }
+ }
+
+ @Override
+ public ActionStatus deleteUserData(String id) {
+ MatchFilter filter = new MatchFilter();
+ filter.addToMatch("userId", id);
+ Neo4jOperationStatus status = neo4jClient.deleteElement(GraphElementTypeEnum.Node, NodeTypeEnum.User.getName(),
+ filter);
+ if (status.equals(Neo4jOperationStatus.OK)) {
+ return ActionStatus.OK;
+ } else {
+ return ActionStatus.GENERAL_ERROR;
+ }
+ }
+
+ public Neo4jClient getNeo4jClient() {
+ return neo4jClient;
+ }
+
+ public void setNeo4jClient(Neo4jClient neo4jClient) {
+ this.neo4jClient = neo4jClient;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchFacet.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchFacet.java
new file mode 100644
index 0000000000..24db9b6912
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchFacet.java
@@ -0,0 +1,55 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.model;
+
+import java.io.Serializable;
+
+/**
+ * A facet informations.
+ *
+ */
+@SuppressWarnings("PMD.UnusedPrivateField")
+public class FacetedSearchFacet implements Serializable {
+ public FacetedSearchFacet(String facetValue, int count) {
+ this.count = count;
+ this.facetValue = facetValue;
+ }
+
+ public String getFacetValue() {
+ return facetValue;
+ }
+
+ public void setFacetValue(String facetValue) {
+ this.facetValue = facetValue;
+ }
+
+ public long getCount() {
+ return count;
+ }
+
+ public void setCount(long count) {
+ this.count = count;
+ }
+
+ private static final long serialVersionUID = 1L;
+ private String facetValue;
+ private long count;
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchResult.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchResult.java
new file mode 100644
index 0000000000..3e14ee7d6c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchResult.java
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.model;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Contains results for a search query.
+ *
+ */
+
+@SuppressWarnings("PMD.UnusedPrivateField")
+public class FacetedSearchResult extends GetMultipleDataResult {
+ private static final long serialVersionUID = 1L;
+
+ private Map<String, FacetedSearchFacet[]> facets;
+
+ /**
+ * Argument constructor.
+ *
+ * @param from
+ * The start index of the returned elements.
+ * @param to
+ * The end index of the returned elements.
+ * @param queryDuration
+ * The duration of the query.
+ * @param totalResults
+ * The total results for this query.
+ * @param types
+ * The types of data found.
+ * @param data
+ * The found data.
+ * @param hashMap
+ * The facets if any for the query.
+ */
+ public FacetedSearchResult(final int from, final int to, final long queryDuration, final long totalResults,
+ final String[] types, final Object[] data, final HashMap<String, FacetedSearchFacet[]> hashMap) {
+ super(types, data, queryDuration, totalResults, from, to);
+ this.facets = hashMap;
+ }
+
+ public Map<String, FacetedSearchFacet[]> getFacets() {
+ return facets;
+ }
+
+ public void setFacets(Map<String, FacetedSearchFacet[]> facets) {
+ this.facets = facets;
+ }
+
+ public FacetedSearchResult() {
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FetchContext.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FetchContext.java
new file mode 100644
index 0000000000..a02c38cf0c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FetchContext.java
@@ -0,0 +1,32 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.model;
+
+public final class FetchContext {
+
+ public static final String QUICK_SEARCH = "quick_search";
+ public static final String TAG_SUGGESTION = "tag_suggestion";
+ public static final String COMPONENT_SUMMARY = "component_summary";
+ public static final String DEPLOYMENT = "deployment";
+
+ private FetchContext() {
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/GetMultipleDataResult.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/GetMultipleDataResult.java
new file mode 100644
index 0000000000..e1e0593a04
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/GetMultipleDataResult.java
@@ -0,0 +1,113 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.model;
+
+import java.io.Serializable;
+
+/**
+ * Result for a multiple data query.
+ *
+ * @author luc boutier
+ */
+@SuppressWarnings("PMD.UnusedPrivateField")
+public class GetMultipleDataResult<T> implements Serializable {
+ public String[] getTypes() {
+ return types;
+ }
+
+ public T[] getData() {
+ return data;
+ }
+
+ public void setTypes(String[] types) {
+ this.types = types.clone();
+ }
+
+ public void setData(T[] data) {
+ this.data = data.clone();
+ }
+
+ public void setQueryDuration(long queryDuration) {
+ this.queryDuration = queryDuration;
+ }
+
+ public void setTotalResults(long totalResults) {
+ this.totalResults = totalResults;
+ }
+
+ public void setFrom(int from) {
+ this.from = from;
+ }
+
+ public void setTo(int to) {
+ this.to = to;
+ }
+
+ public long getQueryDuration() {
+ return queryDuration;
+ }
+
+ public long getTotalResults() {
+ return totalResults;
+ }
+
+ public int getFrom() {
+ return from;
+ }
+
+ public int getTo() {
+ return to;
+ }
+
+ private static final long serialVersionUID = 1L;
+
+ private String[] types;
+ private T[] data;
+ private long queryDuration;
+ private long totalResults;
+ private int from;
+ private int to;
+
+ /**
+ * Construct an object only with data and types
+ *
+ * @param types
+ * @param data
+ */
+ public GetMultipleDataResult(String[] types, T[] data) {
+ this.types = types.clone();
+ this.data = data.clone();
+ }
+
+ public GetMultipleDataResult(String[] types, Object[] data, long queryDuration, long totalResults, int from,
+ int to) {
+
+ this.types = types.clone();
+ this.data = (T[]) data.clone();
+ this.queryDuration = queryDuration;
+ this.totalResults = totalResults;
+ this.from = from;
+ this.to = to;
+ }
+
+ public GetMultipleDataResult() {
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/BatchBuilder.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/BatchBuilder.java
new file mode 100644
index 0000000000..0177d0bd70
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/BatchBuilder.java
@@ -0,0 +1,83 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElement;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+
+public class BatchBuilder {
+ // private Map<String, List<Neo4jNode>> nodes;
+ // private List<Neo4jRelation> relations;
+ //
+ private List<GraphElement> elements;
+
+ // TODO add filter
+
+ protected BatchBuilder() {
+ // nodes = new HashMap<String, List<Neo4jNode>>();
+ // relations = new ArrayList<Neo4jRelation>();
+ elements = new ArrayList<GraphElement>();
+ }
+
+ public static BatchBuilder getBuilder() {
+ return new BatchBuilder();
+ }
+
+ public BatchBuilder add(GraphElement element) {
+ elements.add(element);
+ return this;
+ }
+
+ public List<GraphElement> getElements() {
+ return elements;
+ }
+
+ // public BatchBuilder add( Neo4jNode element ){
+ // String label = element.getLabel();
+ // List<Neo4jNode> list = nodes.get(label);
+ // if ( list == null ){
+ // list = new ArrayList<Neo4jNode>();
+ // }
+ // list.add(element);
+ // nodes.put(label, list);
+
+ // return this;
+ // }
+ // public BatchBuilder add( Neo4jRelation relation ){
+ // relations.add(relation);
+ // return this;
+ // }
+ //
+ // public Map<String, List<Neo4jNode>> getNodes() {
+ // return nodes;
+ // }
+ //
+ // public List<Neo4jRelation> getRelations() {
+ // return relations;
+ // }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTemplates.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTemplates.java
new file mode 100644
index 0000000000..b0b2cc20bb
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTemplates.java
@@ -0,0 +1,52 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+public interface CypherTemplates {
+
+ public static final String CypherUrlTemplate = "http://$host$:$port$/db/data/transaction/commit";
+ public static final String batchTemplate = "http://$host$:$port$/db/data/batch";
+ public static final String getAllIndexsTemplate = "http://$host$:$port$/db/data/schema/index";
+
+ public static final String CypherCreateNodeTemplate = "{\n\"statements\" : [ {\n \"statement\" : \"CREATE (n:$label$ { props } ) RETURN n\",\n \"parameters\" : { \n \"props\" : $props$ \n } } ] }";
+
+ public static final String CypherMatchTemplate = "{\"statements\": [{\"statement\": \"MATCH (n:$label$ {$filter$}) RETURN ($type$) \" }]}";
+
+ public static final String CypherUpdateTemplate = "{\"statements\": [{\"statement\": \"MATCH (n:$label$ {$filter$}) SET n += {props} RETURN ($type$) \",\"parameters\" : {\"props\" : {$props$}}}]}";
+ public static final String CypherDeleteNodeTemplate = "{\"statements\": [{\"statement\": \"MATCH ( n:$label$ {$filter$} ) DELETE n \" }]}";
+
+ public static final String BatchTemplate = "{ \"statements\" : [ $statementList$ ] }";
+
+ public static final String RegularStatementTemplate = "{ \"statement\" : $statement$ }";
+
+ public static final String CreateSingleNodeTemplate = " \"CREATE (n:$label$ { props } ) RETURN n, labels(n)\", \"parameters\" : { \"props\" : $props$ }";
+
+ public static final String CreateRelationTemplate = "\"MATCH (a:$labelFrom$),(b:$labelTo$) WHERE a.$idNameFrom$ = '$idValueFrom$' AND b.$idNameTo$ = '$idvalueTo$' CREATE (a)-[r:$type$ { props } ]->(b) RETURN a, labels(a), b, labels(b), r, type(r)\", \"parameters\": {\"props\": $props$ } ";
+
+ public static final String CreateRelationTemplateNoProps = "\"MATCH (a:$labelFrom$),(b:$labelTo$) WHERE a.$idNameFrom$ = '$idValueFrom$' AND b.$idNameTo$ = '$idvalueTo$' CREATE (a)-[r:$type$ ]->(b) RETURN a,labels(a), b, labels(b), r, type(r)\"";
+
+ public static final String UpdateNodeStatementTemplate = "\"MATCH (n:$label$ {$filter$}) SET n += {props} \",\"parameters\" : {\"props\" : $props$}";
+
+ public static final String GetNodeRecursiveTemplate = "\"MATCH (m:$label$ {$filter$} )-[f$typesList$]->l RETURN m, labels(m), l, labels(l),f, type(f)\"";
+
+ public static final String GetByRelationNodeRecursiveTemplate = "\"MATCH (n:$labelNode$ ($propsNode$} )-[r:$type$ {$propsRel$}]->(m:$labelSrc$)-[f$typesList$]->l RETURN n, labels(n), r, type(r), m, labels(m), l, labels(l),f, type(f)\"";
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTranslator.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTranslator.java
new file mode 100644
index 0000000000..e1409b3bb1
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTranslator.java
@@ -0,0 +1,251 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElement;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint;
+import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter;
+import org.openecomp.sdc.be.dao.neo4j.filters.RecursiveByRelationFilter;
+import org.openecomp.sdc.be.dao.neo4j.filters.RecursiveFilter;
+import org.openecomp.sdc.be.dao.utils.DaoUtils;
+
+public class CypherTranslator {
+
+ public String translate(BatchBuilder builder) {
+ String json = null;
+ StringBuilder statementList = new StringBuilder();
+
+ List<GraphElement> elements = builder.getElements();
+ int statementCounter = 0;
+ for (GraphElement element : elements) {
+ String singleStatementBody = null;
+ switch (element.getElementType()) {
+ case Node:
+ singleStatementBody = prepareNodeStatement(element);
+ break;
+ case Relationship:
+ singleStatementBody = prepareRelationStatement(element);
+ break;
+ }
+ if (singleStatementBody != null && !singleStatementBody.isEmpty()) {
+
+ String singleStatement = CypherTemplates.RegularStatementTemplate.replace("$statement$",
+ singleStatementBody);
+
+ statementList.append(singleStatement);
+ }
+ ++statementCounter;
+ if (statementCounter < elements.size() && singleStatementBody != null) {
+ statementList.append(",");
+ }
+
+ }
+ json = CypherTemplates.BatchTemplate.replace("$statementList$", statementList.toString());
+ return json;
+ }
+
+ private String prepareNodeStatement(GraphElement element) {
+ if (element instanceof GraphNode) {
+ GraphNode node = (GraphNode) element;
+
+ switch (node.getAction()) {
+ case Create:
+ return createNodeStatement(node);
+ case Update:
+ return updateNodeStatement(node);
+ case Delete:
+ // TODO
+ break;
+ default:
+ break;
+ }
+ }
+ return null;
+ }
+
+ private String updateNodeStatement(GraphNode node) {
+ String singleStatement = CypherTemplates.UpdateNodeStatementTemplate.replace("$label$", node.getLabel());
+ String filter = prepareKeyValueFilter(node);
+
+ singleStatement = singleStatement.replace("$filter$", filter);
+
+ singleStatement = singleStatement.replace("$props$", DaoUtils.convertToJson(node.toGraphMap()));
+
+ return singleStatement;
+ }
+
+ private String createNodeStatement(GraphNode node) {
+ String singleStatement = CypherTemplates.CreateSingleNodeTemplate.replace("$label$", node.getLabel());
+
+ singleStatement = singleStatement.replace("$props$", DaoUtils.convertToJson(node.toGraphMap()));
+ return singleStatement;
+ }
+
+ private String prepareRelationStatement(GraphElement element) {
+ if (element instanceof GraphRelation) {
+
+ GraphRelation relation = (GraphRelation) element;
+
+ switch (relation.getAction()) {
+ case Create:
+ return createRelationStatement(relation);
+ case Update:
+ return updateRelationStatement(relation);
+ case Delete:
+ // TODO
+ break;
+ default:
+ break;
+ }
+ }
+ return null;
+ }
+
+ private String createRelationStatement(GraphRelation relation) {
+ RelationEndPoint from = relation.getFrom();
+ String singleStatement;
+
+ Map<String, Object> props = relation.toGraphMap();
+ if (props == null || props.isEmpty()) {
+ singleStatement = CypherTemplates.CreateRelationTemplateNoProps.replace("$labelFrom$",
+ from.getLabel().getName());
+ } else {
+ singleStatement = CypherTemplates.CreateRelationTemplate.replace("$labelFrom$", from.getLabel().getName());
+ singleStatement = singleStatement.replace("$props$", DaoUtils.convertToJson(props));
+ }
+
+ singleStatement = singleStatement.replace("$idNameFrom$", from.getIdName());
+ singleStatement = singleStatement.replace("$idValueFrom$", from.getIdValue().toString());
+
+ RelationEndPoint to = relation.getTo();
+ singleStatement = singleStatement.replace("$labelTo$", to.getLabel().getName());
+ singleStatement = singleStatement.replace("$idNameTo$", to.getIdName());
+ singleStatement = singleStatement.replace("$idvalueTo$", to.getIdValue().toString());
+
+ singleStatement = singleStatement.replace("$type$", relation.getType());
+ return singleStatement;
+ }
+
+ private String updateRelationStatement(GraphRelation relation) {
+ // TODO
+ return null;
+ }
+
+ private String prepareKeyValueFilter(GraphNode node) {
+ StringBuilder sb = new StringBuilder();
+
+ ImmutablePair<String, Object> keyValueId = node.getKeyValueId();
+
+ sb.append(keyValueId.getKey()).append(":");
+ if (keyValueId.getValue() instanceof String) {
+ sb.append("'");
+ }
+ sb.append(keyValueId.getValue());
+
+ if (keyValueId.getValue() instanceof String) {
+ sb.append("'");
+ }
+
+ return sb.toString();
+ }
+
+ public String translateGet(RecursiveFilter filter) {
+ String requestJson = null;
+ String statement;
+
+ if (filter instanceof RecursiveByRelationFilter) {
+ RecursiveByRelationFilter byRelationFilter = (RecursiveByRelationFilter) filter;
+
+ statement = CypherTemplates.GetByRelationNodeRecursiveTemplate.replace("$labelNode$",
+ byRelationFilter.getNode().getLabel());
+ String keyValueId = prepareKeyValueFilter(byRelationFilter.getNode());
+
+ statement = statement.replace("$propsNode$", keyValueId);
+
+ statement = statement.replace("$type$", byRelationFilter.getRelationType());
+
+ String relationProps = prepareFilterBody(filter);
+ statement = statement.replace("$propsRel$", relationProps);
+ statement = statement.replace("$labelSrc$", filter.getNodeType().getName());
+
+ } else {
+
+ statement = CypherTemplates.GetNodeRecursiveTemplate.replace("$label$", filter.getNodeType().getName());
+
+ // replace filter
+ if (filter.getProperties().isEmpty()) {
+ // get all records by label
+ statement = statement.replace("{$filter$}", "");
+ } else {
+ String filterStr = prepareFilterBody(filter);
+ statement = statement.replace("$filter$", filterStr);
+ }
+ }
+
+ if (filter.getChildRelationTypes() == null || filter.getChildRelationTypes().isEmpty()) {
+ statement = statement.replace("$typesList$", "");
+
+ } else {
+ StringBuilder typesList = new StringBuilder();
+ int count = 0;
+ for (String type : filter.getChildRelationTypes()) {
+ typesList.append(":").append(type);
+ ++count;
+ if (count < filter.getChildRelationTypes().size()) {
+ typesList.append("|");
+ }
+ }
+ statement = statement.replace("$typesList$", typesList.toString());
+ }
+ String singleStatement = CypherTemplates.RegularStatementTemplate.replace("$statement$", statement);
+ requestJson = CypherTemplates.BatchTemplate.replace("$statementList$", singleStatement);
+
+ return requestJson;
+ }
+
+ public static String prepareFilterBody(MatchFilter filter) {
+ StringBuilder sb = new StringBuilder();
+ int count = 0;
+ int size = filter.getProperties().entrySet().size();
+ for (Map.Entry<String, Object> entry : filter.getProperties().entrySet()) {
+ sb.append(entry.getKey()).append(":");
+ if (entry.getValue() instanceof String) {
+ sb.append("'");
+ }
+ sb.append(entry.getValue());
+ if (entry.getValue() instanceof String) {
+ sb.append("'");
+ }
+ ++count;
+ if (count < size) {
+ sb.append(",");
+ }
+ }
+ return sb.toString();
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java
new file mode 100644
index 0000000000..917bcbb986
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java
@@ -0,0 +1,101 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public enum GraphEdgeLabels {
+
+ // field name
+ //
+ STATE("STATE"), LAST_STATE("LAST_STATE"), CREATOR("CREATOR"), LAST_MODIFIER("LAST_MODIFIER"), ATTRIBUTE(
+ "EDGE_ATTRIBUTE"), PROPERTY("EDGE_PROPERTY"), CATEGORY("CATEGORY"), DERIVED_FROM(
+ "DERIVED_FROM"), REQUIREMENT("REQUIREMENT"), CAPABILITY_TYPE("CAPABILITY_TYPE"), RELATIONSHIP_TYPE(
+ "RELATIONSHIP_TYPE"), CAPABILITY("CAPABILITY"), INSTANCE_OF("INSTANCE_OF"), INTERFACE(
+ "INTERFACE"), INTERFACE_OPERATION("INTERFACE_OPERATION"), ARTIFACT_REF(
+ "ARTIFACT_REF"), INPUTS("INPUTS"), REQUIREMENT_IMPL(
+ "REQUIREMENT_IMPL"), NODE_IMPL("NODE_IMPL"), IMPLEMENTATION_OF(
+ "IMPLEMENTATION_OF"), ATTRIBUTE_VALUE(
+ "ATTRIBUTE_VALUE"), INPUT_VALUE(
+ "INPUT_VALUE"), PROPERTY_VALUE(
+ "PROPERTY_VALUE"), CAPABILITY_INST(
+ "CAPABILITY_INST"), TYPE_OF(
+ "TYPE_OF"), RESOURCE_INST(
+ "RESOURCE_INST"), RELATIONSHIP_INST(
+ "RELATIONSHIP_INST"), CAPABILITY_NODE(
+ "CAPABILITY_NODE"), LAST_DISTRIBUTION_STATE_MODIFAIER(
+ "LAST_DISTRIBUTION_STATE_MODIFAIER"), ATTRIBUTE_IMPL(
+ "ATTRIBUTE_IMPL"), INPUT_IMPL(
+ "INPUT_IMPL"), PROPERTY_IMPL(
+ "PROPERTY_IMPL"), ADDITIONAL_INFORMATION(
+ "ADDITIONAL_INFORMATION"), HEAT_PARAMETER(
+ "HEAT_PARAMETER"), SUB_CATEGORY(
+ "SUB_CATEGORY"), GROUPING(
+ "GROUPING"), CATEGORIZED_TO(
+ "CATEGORIZED_TO"), GENERATED_FROM(
+ "GENERATED_FROM"), PARAMETER_VALUE(
+ "PARAMETER_VALUE"), PARAMETER_IMPL(
+ "PARAMETER_IMPL"),
+ // VF additions
+ CALCULATED_REQUIREMENT("CALCULATED_REQUIREMENT"), CALCULATED_CAPABILITY(
+ "CALCULATED_CAPABILITY"), RELATIONSHIP_ORIGIN("RELATIONSHIP_ORIGIN"), CAPABILITY_ORIGIN(
+ "CAPABILITY_ORIGIN"), CALCULATED_REQUIREMENT_FULLFILLED(
+ "CALCULATED_REQUIREMENT_FULLFILLED"), CALCULATED_CAPABILITY_FULLFILLED(
+ "CALCULATED_CAPABILITY_FULLFILLED"),
+ // Group
+ GROUP("GROUP"), GROUP_ARTIFACT_REF("GROUP_ARTIFACT_REF"), GROUP_MEMBER("GROUP_MEMBER"), INPUT(
+ "EDGE_INPUT"), GET_INPUT("GET_INPUT"),;
+
+ private String property;
+
+ GraphEdgeLabels(String property) {
+ this.property = property;
+ }
+
+ public String getProperty() {
+ return property;
+ }
+
+ public void setProperty(String property) {
+ this.property = property;
+ }
+
+ public static List<String> getAllProperties() {
+
+ List<String> arrayList = new ArrayList<String>();
+
+ for (GraphEdgeLabels graphProperty : GraphEdgeLabels.values()) {
+ arrayList.add(graphProperty.getProperty());
+ }
+
+ return arrayList;
+ }
+
+ public static GraphEdgeLabels getByName(String property) {
+ for (GraphEdgeLabels inst : GraphEdgeLabels.values()) {
+ if (inst.getProperty().equals(property)) {
+ return inst;
+ }
+ }
+ return null;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java
new file mode 100644
index 0000000000..18c9ecb6f7
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java
@@ -0,0 +1,80 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public enum GraphEdgePropertiesDictionary {
+
+ // field name class type
+ // stored in graph
+ STATE("state", String.class), NAME("name", String.class), GROUP_TYPE("groupType", String.class), SOURCE("source",
+ String.class), OWNER_ID("ownerId", String.class), REQUIRED_OCCURRENCES("requiredOccurrences",
+ String.class), LEFT_OCCURRENCES("leftOccurrences",
+ String.class), GET_INPUT_INDEX("get_input_index", String.class);
+
+ private String property;
+ private Class clazz;
+
+ GraphEdgePropertiesDictionary(String property, Class clazz) {
+ this.property = property;
+ this.clazz = clazz;
+ }
+
+ public String getProperty() {
+ return property;
+ }
+
+ public void setProperty(String property) {
+ this.property = property;
+ }
+
+ public Class getClazz() {
+ return clazz;
+ }
+
+ public void setClazz(Class clazz) {
+ this.clazz = clazz;
+ }
+
+ public static List<String> getAllProperties() {
+
+ List<String> arrayList = new ArrayList<String>();
+
+ for (GraphEdgePropertiesDictionary graphProperty : GraphEdgePropertiesDictionary.values()) {
+ arrayList.add(graphProperty.getProperty());
+ }
+
+ return arrayList;
+ }
+
+ public static GraphEdgePropertiesDictionary getByName(String property) {
+ for (GraphEdgePropertiesDictionary inst : GraphEdgePropertiesDictionary.values()) {
+ if (inst.getProperty().equals(property)) {
+ return inst;
+ }
+ }
+ return null;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphNeighbourTable.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphNeighbourTable.java
new file mode 100644
index 0000000000..ccfb57b145
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphNeighbourTable.java
@@ -0,0 +1,64 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+
+public class GraphNeighbourTable {
+
+ List<GraphNode> nodes = new ArrayList<GraphNode>();
+
+ List<NodeRelation> directedEdges = new ArrayList<NodeRelation>();
+
+ public List<GraphNode> getNodes() {
+ return nodes;
+ }
+
+ public void setNodes(List<GraphNode> nodes) {
+ this.nodes = nodes;
+ }
+
+ public List<NodeRelation> getDirectedEdges() {
+ return directedEdges;
+ }
+
+ public void setDirectedEdges(List<NodeRelation> directedEdges) {
+ this.directedEdges = directedEdges;
+ }
+
+ public int addNode(GraphNode node) {
+ this.nodes.add(node);
+ return this.nodes.size() - 1;
+ }
+
+ public void addEdge(NodeRelation directedEdge) {
+ this.directedEdges.add(directedEdge);
+ }
+
+ @Override
+ public String toString() {
+ return "GraphNeighbourTable [nodes=" + nodes + ", directedEdges=" + directedEdges + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java
new file mode 100644
index 0000000000..a042ab510e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java
@@ -0,0 +1,212 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+import java.util.ArrayList;
+import java.util.List;
+
+
+public enum GraphPropertiesDictionary {
+// field name class type unique indexed
+// stored in graph index
+ // Common
+ LABEL ("nodeLabel", String.class, false, true),
+ HEALTH_CHECK ("healthcheckis", String.class, true, true), //yavivi
+ // Resource
+ NAME ("name", String.class, false, true),
+ TOSCA_RESOURCE_NAME ("toscaResourceName", String.class, false, true),
+ CATEGORY_NAME ("categoryName", String.class, false, true), // ?
+ VERSION ("version", String.class, false, true),
+ CREATION_DATE ("creationDate", Long.class, false, false),
+ LAST_UPDATE_DATE ("modificationDate", Long.class, false, false),
+ IS_HIGHEST_VERSION ("highestVersion", Boolean.class, false, true),
+ IS_ABSTRACT ("abstract", Boolean.class, false, true),
+ DESCRIPTION ("description", String.class, false, false),
+ UNIQUE_ID ("uid", String.class, true, true),
+ STATE ("state", String.class, false, true),
+ TYPE ("type", String.class, false, true),
+ REQUIRED ("required", Boolean.class, false, false),
+ DEFAULT_VALUE ("defaultValue", String.class, false, false),
+ CONSTRAINTS ("constraints", String.class, false, false),
+ CONTACT_ID ("contactId", String.class, false, false),
+ VENDOR_NAME ("vendorName", String.class, false, false),
+ VENDOR_RELEASE ("vendorRelease", String.class, false, false),
+ ICON ("icon", String.class, false, false),
+ TAGS ("tags", String.class, false, false),
+ UUID ("uuid", String.class, false, true),
+ COST ("cost", String.class, false, false),
+ LICENSE_TYPE ("licenseType", String.class, false, false),
+ NORMALIZED_NAME ("normalizedName", String.class, false, true),
+ SYSTEM_NAME ("systemName", String.class, false, true),
+ IS_DELETED ("deleted", Boolean.class, false, true),
+ RESOURCE_TYPE ("resourceType", String.class, false, true),
+ ENTRY_SCHEMA ("entry_schema", String.class, false, false),
+ CSAR_UUID ("csarUuid", String.class, false, true),
+ CSAR_VERSION ("csarVersion", String.class, false, true),
+ IMPORTED_TOSCA_CHECKSUM ("importedToscaChecksum", String.class, false, true),
+ GENERATED ("generated", Boolean.class, false, false),
+ // User
+ USER_ID ("userId", String.class, true, true),
+ EMAIL ("email", String.class, false, false),
+ FIRST_NAME ("firstName", String.class, false, false),
+ LAST_NAME ("lastName", String.class, false, false),
+ ROLE ("role", String.class, false, true),
+ USER_STATUS ("status", String.class, false, true),
+ VALID_SOURCE_TYPES ("validSourceTypes", String.class, false, false),
+ NODE ("node", String.class, false, false),
+ VALUE ("value", String.class, false, false),
+ HIDDEN ("Hidden", Boolean.class, false, false),
+ PROPERTIES ("properties", String.class, false, false),
+ POSITION_X ("positionX", String.class, false, false),
+ POSITION_Y ("positionY", String.class, false, false),
+ RELATIONSHIP_TYPE ("relationshipType", String.class, false, false),
+ ARTIFACT_TYPE ("artifactType", String.class, false, true),
+ ARTIFACT_REF ("artifactRef", String.class, false, false),
+ ARTIFACT_REPOSITORY ("artifactRepository", String.class, false, false),
+ ARTIFACT_CHECKSUM ("artifactChecksum", String.class, false, false),
+ CREATOR ("creator", String.class, false, false),
+ ATT_CREATOR ("attCreator", String.class, false, false),
+ LAST_UPDATER ("lastUpdater", String.class, false, false),
+ CREATOR_FULL_NAME ("creatorFullName", String.class, false, false),
+ UPDATER_FULL_NAME ("updaterFullName", String.class, false, false),
+ ES_ID ("esId", String.class, false, false),
+ ARTIFACT_LABEL ("artifactLabel", String.class, false, true),
+ ARTIFACT_DISPLAY_NAME("artifactDisplayName", String.class, false, true),
+ INSTANCE_COUNTER ("instanceCounter", Integer.class, false, false),
+ PROJECT_CODE ("projectCode", String.class, false, false),
+ DISTRIBUTION_STATUS ("distributionStatus", String.class, false, false),
+ IS_VNF ("isVNF", Boolean.class, false, false),
+ LAST_LOGIN_TIME ("lastLoginTime", Long.class, false, true),
+ ATTRIBUTE_COUNTER ("attributeCounter", Integer.class, false, false),
+ INPUT_COUNTER ("inputCounter", Integer.class, false, false),
+ PROPERTY_COUNTER ("propertyCounter", Integer.class, false, false),
+ API_URL ("apiUrl", String.class, false, false),
+ SERVICE_API ("serviceApi", Boolean.class, false, true),
+ ADDITIONAL_INFO_PARAMS ("additionalInfo", String.class, false, false),
+ ADDITIONAL_INFO_ID_TO_KEY ("idToKey", String.class, false, false),
+ ARTIFACT_GROUP_TYPE ("artifactGroupType", String.class, false, true),
+ ARTIFACT_TIMEOUT ("timeout", Integer.class, false, false),
+ IS_ACTIVE ("isActive", Boolean.class, false, true),
+ PROPERTY_VALUE_RULES ("propertyValueRules", String.class, false, false),
+ //authantication
+ CONSUMER_NAME ("consumerName", String.class, true, true),
+ CONSUMER_PASSWORD ("consumerPassword", String.class, false, false),
+ CONSUMER_SALT ("consumerSalt", String.class, false, false),
+ CONSUMER_LAST_AUTHENTICATION_TIME ("consumerLastAuthenticationTime", Long.class, false, false),
+ CONSUMER_DETAILS_LAST_UPDATED_TIME ("consumerDetailsLastupdatedtime", Long.class, false, false),
+ LAST_MODIFIER_USER_ID("lastModfierUserId", String.class, false, false),
+ ARTIFACT_VERSION ("artifactVersion", String.class, false, false),
+ ARTIFACT_UUID ("artifactUUID", String.class, false, false),
+ PAYLOAD_UPDATE_DATE ("payloadUpdateDate", Long.class, false, false),
+ HEAT_PARAMS_UPDATE_DATE ("heatParamsUpdateDate",Long.class, false, false),
+ //product
+ FULL_NAME ("fullName", String.class, false, true),
+ //was changed as part of migration from 1602 to 1602 ( in 1602 was defined as unique. it's problem to reconfigure the index )
+ CONSTANT_UUID ("constantUuidNew", String.class, false, true),
+ CONTACTS ("contacts", String.class, false, false),
+ //categorys
+ ICONS ("icons", String.class, false, false),
+ //relation
+ CAPABILITY_OWNER_ID ("capOwnerId", String.class, false, false),
+ REQUIREMENT_OWNER_ID ("reqOwnerId", String.class, false, false),
+ CAPABILITY_ID ("capabiltyId", String.class, false, false),
+ REQUIREMENT_ID ("requirementId", String.class, false, false),
+ PROPERTY_ID ("propertyId", String.class, false, false),
+ PROPERTY_NAME ("propertyName", String.class, false, false),
+ //component instance
+ ORIGIN_TYPE ("originType", String.class, false, false),
+ //requirement & capabilty
+ MIN_OCCURRENCES ("minOccurrences", String.class, false, false),
+ MAX_OCCURRENCES ("maxOccurrences", String.class, false, false),
+ //Data type
+ DERIVED_FROM ("derivedFrom", String.class, false, false),
+ MEMBERS ("members", String.class, false, false),
+ TARGETS ("targets ", String.class, false, false),
+ METADATA ("metadata", String.class, false, false),
+ INVARIANT_UUID ("invariantUuid", String.class, false, true),
+ IS_BASE ("isBase", Boolean.class, false, true),
+ GROUP_UUID ("groupUuid", String.class, false, true),
+ STATUS ("status", String.class, false, false),
+ FUNCTIONAL_MENU ("functionalMenu", String.class, false, false),
+ REQUIRED_ARTIFACTS ("requiredArtifacts", String.class, false, false),
+ ;
+
+
+
+ private String property;
+ private Class clazz;
+ private boolean unique;
+ private boolean indexed;
+
+
+ GraphPropertiesDictionary(String property,Class clazz, boolean unique,boolean indexed) {
+ this.property = property;
+ this.clazz = clazz;
+ this.unique = unique;
+ this.indexed = indexed;
+ }
+
+
+ public String getProperty() {
+ return property;
+ }
+
+ public void setProperty(String property) {
+ this.property = property;
+ }
+
+ public Class getClazz() {
+ return clazz;
+ }
+ public void setClazz(Class clazz) {
+ this.clazz = clazz;
+ }
+
+ public boolean isUnique() {
+ return unique;
+ }
+ public void setUnique(boolean unique) {
+ this.unique = unique;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+
+
+ public void setIndexed(boolean indexed) {
+ this.indexed = indexed;
+ }
+
+
+ public static List<String> getAllProperties() {
+
+ List<String> arrayList = new ArrayList<String>();
+
+ for (GraphPropertiesDictionary graphProperty : GraphPropertiesDictionary
+ .values()) {
+ arrayList.add(graphProperty.getProperty());
+ }
+
+ return arrayList;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java
new file mode 100644
index 0000000000..8bab8d8a8f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java
@@ -0,0 +1,1004 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.AuthCache;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.client.HttpResponseException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.auth.BasicScheme;
+import org.apache.http.impl.client.BasicAuthCache;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.apache.http.impl.client.BasicResponseHandler;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.util.EntityUtils;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElement;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter;
+import org.openecomp.sdc.be.dao.neo4j.filters.RecursiveFilter;
+import org.openecomp.sdc.be.dao.neo4j.filters.UpdateFilter;
+import org.openecomp.sdc.be.dao.utils.DaoUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import fj.data.Either;
+
+//@Component("neo4j-client")
+public class Neo4jClient {
+ private CloseableHttpClient httpClient;
+ private JSONParser jsonParser;
+
+ private CypherTranslator cypherTranslator;
+
+ private static Logger logger = LoggerFactory.getLogger(Neo4jClient.class.getName());
+
+ private static final String getServiceRoot = "http://$host$:$port$/db/data/";
+ // Error's Classification templates
+ private static final String ClientError = "ClientError";
+ private static final String DatabaseError = "DatabaseError";
+ private static final String TransientError = "TransientError";
+
+ // Error's Category templates
+ private static final String General = "General";
+ private static final String LegacyIndex = "LegacyIndex";
+ private static final String Request = "Request";
+ private static final String Schema = "Schema";
+ private static final String Security = "Security";
+ private static final String Statement = "Statement";
+ private static final String Transaction = "Transaction";
+
+ // Error's Title templates
+ private static final String EntityNotFound = "EntityNotFound";
+ private static final String ConstraintViolation = "ConstraintViolation";
+
+ @PostConstruct
+ public void init() {
+
+ PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
+ connectionManager.setMaxTotal(100);
+ connectionManager.setDefaultMaxPerRoute(20);
+ connectionManager.setValidateAfterInactivity(15000);
+ this.httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
+ jsonParser = new JSONParser();
+ cypherTranslator = new CypherTranslator();
+
+ }
+
+ @PreDestroy
+ public void shutdown() {
+ try {
+ httpClient.close();
+ logger.debug("Http client to Neo4j Graph closed");
+ } catch (Exception e) {
+ logger.info("Failed to close http client", e);
+ }
+ }
+
+ /**
+ *
+ * @param builder
+ * @return
+ */
+ public Either<List<List<GraphElement>>, Neo4jOperationStatus> execute(BatchBuilder builder) {
+
+ String json = cypherTranslator.translate(builder);
+ logger.debug("Try to execute cypher request [ {} ]", json);
+
+ Either<String, Neo4jOperationStatus> result = sendPostCypher(json);
+ if (result.isRight()) {
+ return Either.right(result.right().value());
+ }
+ List<List<GraphElement>> batchResult;
+ try {
+ batchResult = parseResult(result.left().value(), false);
+ } catch (ParseException e) {
+ logger.error("Failed to parse batchresponse", e);
+ return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
+ }
+
+ return Either.left(batchResult);
+ }
+
+ public Either<List<List<GraphElement>>, Neo4jOperationStatus> executeGet(RecursiveFilter filter) {
+ String json = cypherTranslator.translateGet(filter);
+ logger.debug("Try to execute cypher request [ {} ]", json);
+
+ Either<String, Neo4jOperationStatus> result = sendPostCypher(json);
+ if (result.isRight()) {
+ return Either.right(result.right().value());
+ }
+ List<List<GraphElement>> batchResult;
+ try {
+ batchResult = parseResult(result.left().value(), true);
+ } catch (ParseException e) {
+ logger.error("Failed to parse batchresponse", e);
+ return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
+ }
+
+ return Either.left(batchResult);
+
+ }
+
+ /**
+ *
+ * @param element
+ * @param ip
+ * @param user
+ * @param password
+ * @return
+ */
+ public Neo4jOperationStatus createElement(GraphElement element) {
+ Neo4jOperationStatus result = Neo4jOperationStatus.OK;
+ switch (element.getElementType()) {
+ case Node:
+ Either<String, Neo4jOperationStatus> status = createNode(element);
+ if (status.isRight()) {
+ result = status.right().value();
+ }
+ break;
+ case Relationship:
+ // TODO
+ break;
+
+ default:
+ break;
+ }
+
+ return result;
+ }
+
+ public Either<GraphElement, Neo4jOperationStatus> createSingleElement(GraphElement element) {
+ switch (element.getElementType()) {
+ case Node:
+ Either<String, Neo4jOperationStatus> status = createNode(element);
+ if (status.isRight()) {
+ return Either.right(status.right().value());
+ }
+ // parse response
+ String response = status.left().value();
+ try {
+ List<GraphElement> listElements = parseGetResponse(element.getElementType(),
+ ((GraphNode) element).getLabel(), response);
+ if (listElements == null || listElements.isEmpty()) {
+ return Either.right(Neo4jOperationStatus.NOT_FOUND);
+ } else {
+ return Either.left(listElements.get(0));
+ }
+ } catch (Exception e) {
+ logger.error("Failed to parse fetched data from graph", e);
+ return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
+ }
+ case Relationship:
+ // TODO
+ break;
+
+ default:
+ break;
+ }
+
+ return Either.right(Neo4jOperationStatus.NOT_SUPPORTED);
+ }
+
+ /**
+ *
+ * @param type
+ * @param label
+ * @param filter
+ * @param ip
+ * @param user
+ * @param password
+ * @return
+ */
+ public Either<List<GraphElement>, Neo4jOperationStatus> getByFilter(GraphElementTypeEnum type, String label,
+ MatchFilter filter) {
+
+ List<GraphElement> result = null;
+
+ String requestJson;
+ // replace return type
+ if (type.equals(GraphElementTypeEnum.Node)) {
+ requestJson = CypherTemplates.CypherMatchTemplate.replace("$type$", "n");
+ } else {
+ requestJson = CypherTemplates.CypherMatchTemplate.replace("$type$", "r");
+ }
+ // replace label
+ if (label != null && !label.isEmpty()) {
+ requestJson = requestJson.replace("$label$", label);
+ } else {
+ requestJson = requestJson.replace("$label$", "");
+ }
+
+ // replace filter
+ if (filter.getProperties().isEmpty()) {
+ // get all records by label
+ requestJson = requestJson.replace("{$filter$}", "");
+ } else {
+ String filterStr = CypherTranslator.prepareFilterBody(filter);
+ requestJson = requestJson.replace("$filter$", filterStr);
+ }
+ logger.debug("Try to perform request [ {} ]", requestJson);
+
+ Either<String, Neo4jOperationStatus> status = sendPostCypher(requestJson);
+ if (status.isRight()) {
+ return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
+ }
+ // parse response
+ String response = status.left().value();
+ try {
+ result = parseGetResponse(type, label, response);
+ } catch (Exception e) {
+ logger.error("Failed to parse fetched data from graph", e);
+ Either.right(Neo4jOperationStatus.GENERAL_ERROR);
+ }
+
+ return Either.left(result);
+ }
+
+ /**
+ *
+ * @param type
+ * @param label
+ * @param toMatch
+ * @param toUpdate
+ * @param ip
+ * @param user
+ * @param password
+ * @return
+ */
+ public Neo4jOperationStatus updateElement(GraphElementTypeEnum type, String label, UpdateFilter toUpdate) {
+
+ String requestJson;
+ // replace return type
+ if (type.equals(GraphElementTypeEnum.Node)) {
+ requestJson = CypherTemplates.CypherUpdateTemplate.replace("$type$", "n");
+ } else {
+ requestJson = CypherTemplates.CypherUpdateTemplate.replace("$type$", "r");
+ }
+ // replace label
+ if (label != null && !label.isEmpty()) {
+ requestJson = requestJson.replace("$label$", label);
+ } else {
+ requestJson = requestJson.replace("$label$", "");
+ }
+
+ // replace filter
+ if (toUpdate.getProperties().isEmpty()) {
+ // get all records by label
+ requestJson = requestJson.replace("{$filter$}", "");
+ } else {
+ String filterStr = CypherTranslator.prepareFilterBody(toUpdate);
+ requestJson = requestJson.replace("$filter$", filterStr);
+ }
+ String props = preparePropertiesInStatement(toUpdate.getToUpdate());
+ requestJson = requestJson.replace("$props$", props);
+
+ logger.debug("Try to perform request [ {} ]", requestJson);
+
+ Either<String, Neo4jOperationStatus> result = sendPostCypher(requestJson);
+ if (result.isRight()) {
+ return Neo4jOperationStatus.GENERAL_ERROR;
+ }
+ return Neo4jOperationStatus.OK;
+ }
+
+ /**
+ *
+ * @param type
+ * @param label
+ * @param response
+ * @return
+ * @throws ParseException
+ */
+
+ private List<GraphElement> parseGetResponse(GraphElementTypeEnum type, String label, String response)
+ throws ParseException {
+ List<GraphElement> result = new ArrayList<GraphElement>();
+ JSONObject responseData = (JSONObject) jsonParser.parse(response);
+ JSONArray results = (JSONArray) responseData.get("results");
+ Iterator<JSONObject> iteratorResults = results.iterator();
+ while (iteratorResults.hasNext()) {
+ JSONObject elementResult = iteratorResults.next();
+ // JSONArray data = (JSONArray) elementResult.get("row");
+ JSONArray data = (JSONArray) elementResult.get("data");
+
+ Iterator<JSONObject> iterator = data.iterator();
+ JSONObject element;
+ while (iterator.hasNext()) {
+ element = (JSONObject) iterator.next();
+ JSONArray row = (JSONArray) element.get("row");
+
+ Iterator<JSONObject> iteratorRow = row.iterator();
+ while (iteratorRow.hasNext()) {
+ JSONObject rowElement = iteratorRow.next();
+
+ Map<String, Object> props = new HashMap<String, Object>();
+
+ for (Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>) rowElement.entrySet()) {
+ // props.put(entry.getKey(),
+ // rowElement.get(entry.getValue()));
+ props.put(entry.getKey(), entry.getValue());
+ }
+ GraphElement newElement = GraphElementFactory.createElement(label, type, props);
+ result.add(newElement);
+ }
+ }
+ }
+ return result;
+ }
+
+ private List<List<GraphElement>> parseResult(String response, boolean storeRelationNode) throws ParseException {
+
+ List<List<GraphElement>> batchList = new ArrayList<List<GraphElement>>();
+
+ JSONObject responseData = (JSONObject) jsonParser.parse(response);
+ JSONArray results = (JSONArray) responseData.get("results");
+ Iterator<JSONObject> iteratorResults = results.iterator();
+
+ while (iteratorResults.hasNext()) {
+ JSONObject elementResult = iteratorResults.next();
+ JSONArray data = (JSONArray) elementResult.get("data");
+ JSONArray columns = (JSONArray) elementResult.get("columns");
+ Iterator<JSONObject> iteratorData = data.iterator();
+ List<GraphElement> singleDataList = new ArrayList<GraphElement>();
+ while (iteratorData.hasNext()) {
+
+ JSONObject singleData = iteratorData.next();
+ JSONArray row = (JSONArray) singleData.get("row");
+ if (columns.size() == 2) {
+ // node
+ JSONArray labelArray = (JSONArray) row.get(1);
+ JSONObject node = (JSONObject) row.get(0);
+
+ Map<String, Object> props = jsonObjectToMap(node);
+ // get only first label on node. Now single label supported
+ GraphElement newElement = GraphElementFactory.createElement((String) labelArray.get(0),
+ GraphElementTypeEnum.Node, props);
+ singleDataList.add(newElement);
+ }
+ if (columns.size() == 10) {
+ // relation
+ JSONObject startNode = (JSONObject) row.get(0);
+ JSONArray startNodeArray = (JSONArray) row.get(1);
+
+ JSONObject relationFromStart = (JSONObject) row.get(2);
+ String relationFromStartType = (String) row.get(3);
+
+ JSONObject nodeFrom = (JSONObject) row.get(4);
+ JSONArray labelFromArray = (JSONArray) row.get(5);
+
+ JSONObject nodeTo = (JSONObject) row.get(6);
+ JSONArray labelToArray = (JSONArray) row.get(7);
+
+ JSONObject relation = (JSONObject) row.get(8);
+ String type = (String) row.get(9);
+
+ Map<String, Object> propsStartNode = jsonObjectToMap(startNode);
+ Map<String, Object> propsRelationStartNode = jsonObjectToMap(relationFromStart);
+
+ Map<String, Object> propsFrom = jsonObjectToMap(nodeFrom);
+ Map<String, Object> propsTo = jsonObjectToMap(nodeTo);
+ Map<String, Object> propsRelation = jsonObjectToMap(relation);
+
+ GraphNode startN = (GraphNode) GraphElementFactory.createElement((String) startNodeArray.get(0),
+ GraphElementTypeEnum.Node, propsStartNode);
+
+ GraphNode from = (GraphNode) GraphElementFactory.createElement((String) labelFromArray.get(0),
+ GraphElementTypeEnum.Node, propsFrom);
+ GraphNode to = (GraphNode) GraphElementFactory.createElement((String) labelToArray.get(0),
+ GraphElementTypeEnum.Node, propsTo);
+
+ singleDataList.add(startN);
+
+ GraphElement relationFromStartNode = GraphElementFactory.createRelation(type,
+ propsRelationStartNode, startN, from);
+ singleDataList.add(relationFromStartNode);
+
+ singleDataList.add(from);
+ singleDataList.add(to);
+ // get only first type on relationship. Now single type
+ // supported
+ GraphElement newElement = GraphElementFactory.createRelation(type, propsRelation, from, to);
+ singleDataList.add(newElement);
+ }
+ if (columns.size() == 8) {
+
+ }
+ }
+ batchList.add(singleDataList);
+ }
+ return batchList;
+ }
+
+ private Map<String, Object> jsonObjectToMap(JSONObject node) {
+ Map<String, Object> props = new HashMap<String, Object>();
+
+ for (Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>) node.entrySet()) {
+ props.put(entry.getKey(), entry.getValue());
+ }
+ return props;
+ }
+
+ private String preparePropertiesInStatement(Map<String, Object> properties) {
+ StringBuilder sb = new StringBuilder();
+ int count = 0;
+ int size = properties.entrySet().size();
+ for (Map.Entry<String, Object> entry : properties.entrySet()) {
+ sb.append("\"").append(entry.getKey()).append("\"").append(":");
+ if (entry.getValue() instanceof String) {
+ sb.append("\"");
+ }
+ sb.append(entry.getValue());
+ if (entry.getValue() instanceof String) {
+ sb.append("\"");
+ }
+ ++count;
+ if (count < size) {
+ sb.append(",");
+ }
+ }
+ return sb.toString();
+ }
+
+ private Either<String, Neo4jOperationStatus> createNode(GraphElement element) {
+ Either<String, Neo4jOperationStatus> status;
+ if (element instanceof GraphNode) {
+ GraphNode node = (GraphNode) element;
+ String json = prepareCreateNodeBody(node);
+
+ logger.debug("Try to save Node [ {} ]", json);
+
+ status = sendPostCypher(json);
+
+ return status;
+
+ } else {
+ return Either.right(Neo4jOperationStatus.WRONG_INPUT);
+ }
+ }
+
+ private Either<String, Neo4jOperationStatus> sendPostCypher(String json) {
+ Map<String, Object> neo4jParams = ConfigurationManager.getConfigurationManager().getConfiguration().getNeo4j();
+ String host = (String) neo4jParams.get("host");
+ Integer port = (Integer) neo4jParams.get("port");
+ String user = (String) neo4jParams.get("user");
+ String password = (String) neo4jParams.get("password");
+
+ String uri = CypherTemplates.CypherUrlTemplate.replace("$host$", host);
+ uri = uri.replace("$port$", port.toString());
+
+ HttpClientContext context = creatClientContext(host, user, password);
+ CloseableHttpResponse response = null;
+
+ HttpPost post = new HttpPost(uri);
+ try {
+ StringEntity input = new StringEntity(json);
+ input.setContentType("application/json");
+ post.setEntity(input);
+
+ response = httpClient.execute(post, context);
+
+ int status = response.getStatusLine().getStatusCode();
+ String responseString;
+ responseString = new BasicResponseHandler().handleResponse(response);
+ logger.debug("response [ {} ]", responseString);
+
+ if (status == 200 || status == 201) {
+ logger.debug("cypher request [ {} ]", json);
+ Neo4jOperationStatus responseStatus = checkResponse(responseString);
+ if (Neo4jOperationStatus.OK.equals(responseStatus)) {
+ return Either.left(responseString);
+ } else {
+ return Either.right(responseStatus);
+ }
+ } else {
+ logger.debug("cypher request [ {} ] was failed: [ {} ]", json, responseString);
+ return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
+ }
+
+ } catch (HttpResponseException e) {
+ logger.debug("failed to perform cypher request [ {} ], {}", json, e);
+ if (e.getStatusCode() == 401) {
+ return Either.right(Neo4jOperationStatus.NOT_AUTHORIZED);
+ } else {
+ return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
+ }
+ } catch (ClientProtocolException e) {
+ logger.debug("failed to perform cypher request [ {} ] {}", json, e);
+ return Either.right(Neo4jOperationStatus.HTTP_PROTOCOL_ERROR);
+ } catch (IOException e) {
+ logger.debug("failed to perform cypher request [ {} ] {}", json, e);
+ return Either.right(Neo4jOperationStatus.NOT_CONNECTED);
+ } finally {
+ releaseResource(response);
+ }
+ }
+
+ private Neo4jOperationStatus checkResponse(String responseString) {
+ try {
+ JSONObject response = (JSONObject) jsonParser.parse(responseString);
+ JSONArray errors = (JSONArray) response.get("errors");
+ if (errors.size() == 0) {
+ return Neo4jOperationStatus.OK;
+ } else {
+ Iterator<JSONObject> iterator = errors.iterator();
+ JSONObject error;
+ while (iterator.hasNext()) {
+ error = (JSONObject) iterator.next();
+ String code = (String) error.get("code");
+ String message = (String) error.get("message");
+
+ Neo4jOperationStatus neoError = mapToNeoError(code, message);
+ return neoError;
+ }
+ return Neo4jOperationStatus.GENERAL_ERROR;
+ }
+ } catch (ParseException e) {
+ logger.error("Failed to parse response", e);
+ return Neo4jOperationStatus.GENERAL_ERROR;
+ }
+ }
+
+ private Neo4jOperationStatus mapToNeoError(String code, String message) {
+ Neo4jOperationStatus error;
+
+ String[] errorCode = code.split("\\.");
+ if (errorCode.length < 4) {
+ error = Neo4jOperationStatus.GENERAL_ERROR;
+ } else {
+ // by Classification
+ switch (errorCode[1]) {
+ case ClientError:
+ // by Category
+ switch (errorCode[2]) {
+ case General:
+ error = Neo4jOperationStatus.DB_READ_ONLY;
+ break;
+ case LegacyIndex:
+ error = Neo4jOperationStatus.LEGACY_INDEX_ERROR;
+ break;
+ case Request:
+ error = Neo4jOperationStatus.BAD_REQUEST;
+ break;
+ case Schema:
+ if (errorCode[3].equals(ConstraintViolation)) {
+ error = Neo4jOperationStatus.ENTITY_ALREADY_EXIST;
+ } else {
+ error = Neo4jOperationStatus.SCHEMA_ERROR;
+ }
+ break;
+ case Security:
+ error = Neo4jOperationStatus.NOT_AUTHORIZED;
+ break;
+ case Statement:
+ // by Title
+ if (errorCode[3].equals(EntityNotFound)) {
+ error = Neo4jOperationStatus.NOT_FOUND;
+ } else {
+ if (errorCode[3].equals(ConstraintViolation)) {
+ error = Neo4jOperationStatus.ENTITY_ALREADY_EXIST;
+ } else {
+ error = Neo4jOperationStatus.BAD_REQUEST;
+ }
+ }
+ break;
+ case Transaction:
+ error = Neo4jOperationStatus.TRANSACTION_ERROR;
+ break;
+ default:
+ error = Neo4jOperationStatus.GENERAL_ERROR;
+ break;
+ }
+ break;
+ case DatabaseError:
+ // by Category
+ switch (errorCode[2]) {
+ case General:
+ error = Neo4jOperationStatus.GENERAL_ERROR;
+ break;
+ case Schema:
+ error = Neo4jOperationStatus.SCHEMA_ERROR;
+ break;
+ case Statement:
+ error = Neo4jOperationStatus.EXECUTION_FAILED;
+ break;
+ case Transaction:
+ error = Neo4jOperationStatus.TRANSACTION_ERROR;
+ break;
+ default:
+ error = Neo4jOperationStatus.GENERAL_ERROR;
+ break;
+ }
+ break;
+ case TransientError:
+ error = Neo4jOperationStatus.DB_NOT_AVAILABLE;
+ break;
+ default:
+ error = Neo4jOperationStatus.GENERAL_ERROR;
+ break;
+ }
+ error.setOriginError(code).setMessage(message);
+ String errorFromCfg = code.replace(".", "_");
+ String helpMessage = ConfigurationManager.getConfigurationManager().getNeo4jErrorsConfiguration()
+ .getErrorMessage(errorFromCfg);
+ if (helpMessage != null && !helpMessage.isEmpty()) {
+ error.setHelpErrorMsg(helpMessage);
+ }
+ }
+ return error;
+ }
+
+ private String prepareCreateNodeBody(GraphNode node) {
+
+ String body = CypherTemplates.CypherCreateNodeTemplate.replace("$label$", node.getLabel());
+
+ body = body.replace("$props$", DaoUtils.convertToJson(node.toGraphMap()));
+
+ return body;
+ }
+
+ /**
+ * the method returns all the indexes for the given label if no label is
+ * supplied ( null or "") all indexes will be returned
+ *
+ * @param label
+ * the name of the label
+ * @param ip
+ * @param user
+ * @param password
+ * @return a map of labels and there properties
+ */
+ public Either<Map<String, List<String>>, Neo4jOperationStatus> getIndexes(String label) {
+ Map<String, Object> neo4jParams = ConfigurationManager.getConfigurationManager().getConfiguration().getNeo4j();
+ String host = (String) neo4jParams.get("host");
+ Integer port = (Integer) neo4jParams.get("port");
+ String user = (String) neo4jParams.get("user");
+ String password = (String) neo4jParams.get("password");
+
+ String uri = null;
+ if (label == null || "".equals(label)) {
+ uri = CypherTemplates.getAllIndexsTemplate.replace("$host$", host);
+ } else {
+ uri = CypherTemplates.getAllIndexsTemplate.replace("$host$", host) + "/" + label;
+ }
+ uri = uri.replace("$port$", port.toString());
+
+ HttpClientContext context = creatClientContext(host, user, password);
+ CloseableHttpResponse response = null;
+
+ HttpGet get = new HttpGet(uri);
+ get.setHeader("Content-Type", "application/json");
+ get.setHeader("Accept", "application/json; charset=UTF-8");
+
+ try {
+
+ response = httpClient.execute(get, context);
+ int statusCode = response.getStatusLine().getStatusCode();
+ if (statusCode != 200) {
+ logger.error("failed to get indexes requeste returned " + statusCode);
+ return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
+ } else {
+ Map<String, List<String>> labels = getLeablesFromJson(response);
+ return Either.left(labels);
+ }
+ } catch (Exception e) {
+ logger.debug("failed to get indexes ", e);
+ return Either.right(Neo4jOperationStatus.GENERAL_ERROR);
+ } finally {
+ releaseResource(response);
+
+ }
+
+ }
+
+ private Map<String, List<String>> getLeablesFromJson(CloseableHttpResponse response)
+ throws HttpResponseException, IOException, ParseException {
+ Map<String, List<String>> labels = new HashMap<>();
+ String responseString = new BasicResponseHandler().handleResponse(response);
+ JSONArray results = (JSONArray) jsonParser.parse(responseString);
+ Iterator<JSONObject> iteratorResults = results.iterator();
+ while (iteratorResults.hasNext()) {
+ JSONObject elementResult = iteratorResults.next();
+ String label = (String) elementResult.get("label");
+ List<String> props = labels.get(label);
+ if (props == null) {
+ props = new ArrayList<>();
+ labels.put(label, props);
+ }
+ JSONArray properties = (JSONArray) elementResult.get("property_keys");
+ Iterator<String> iterator = properties.iterator();
+ while (iterator.hasNext()) {
+ props.add(iterator.next());
+ }
+ }
+ return labels;
+ }
+
+ public Neo4jOperationStatus createIndex(String label, List<String> propertyNames) {
+
+ Neo4jOperationStatus result = Neo4jOperationStatus.OK;
+ if (propertyNames != null && !propertyNames.isEmpty()) {
+
+ Map<String, Object> neo4jParams = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getNeo4j();
+ String host = (String) neo4jParams.get("host");
+ Integer port = (Integer) neo4jParams.get("port");
+ String user = (String) neo4jParams.get("user");
+ String password = (String) neo4jParams.get("password");
+
+ String uri = CypherTemplates.batchTemplate.replace("$host$", host);
+ uri = uri.replace("$port$", port.toString());
+
+ String opertionUri = "/schema/index/" + label;
+
+ HttpClientContext context = creatClientContext(host, user, password);
+
+ CloseableHttpResponse response = null;
+
+ HttpPost post = new HttpPost(uri);
+
+ String json = createBatchJson(HttpMethod.POST, opertionUri, propertyNames);
+
+ try {
+ StringEntity input = new StringEntity(json);
+ input.setContentType("application/json");
+ post.setEntity(input);
+ response = httpClient.execute(post, context);
+ int statusCode = response.getStatusLine().getStatusCode();
+ if (statusCode != 200) {
+ logger.error("failed to create index for label [" + label + "] with properties:" + propertyNames
+ + " requeste returned " + statusCode);
+ result = Neo4jOperationStatus.GENERAL_ERROR;
+ } else {
+ logger.debug("index for label [ {} ] with properties {} created", label, propertyNames);
+ }
+ } catch (Exception e) {
+ logger.debug("failed to create index for label [ {} ] with properties {}", label, propertyNames);
+ result = Neo4jOperationStatus.GENERAL_ERROR;
+ } finally {
+
+ releaseResource(response);
+
+ }
+
+ }
+
+ else {
+ logger.debug("no index was created for label: {}, the received propertyNames list: {} is invalid", label, propertyNames);
+ return Neo4jOperationStatus.WRONG_INPUT;
+ }
+
+ return result;
+ }
+
+ public Neo4jOperationStatus createUniquenessConstraints(String label, List<String> propertyNames) {
+ Neo4jOperationStatus result = Neo4jOperationStatus.OK;
+ if (propertyNames != null && !propertyNames.isEmpty()) {
+
+ Map<String, Object> neo4jParams = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getNeo4j();
+ String host = (String) neo4jParams.get("host");
+ Integer port = (Integer) neo4jParams.get("port");
+ String user = (String) neo4jParams.get("user");
+ String password = (String) neo4jParams.get("password");
+
+ String uri = CypherTemplates.batchTemplate.replace("$host$", host);
+ uri = uri.replace("$port$", port.toString());
+
+ String opertionUri = "/schema/constraint/" + label + "/uniqueness/";
+
+ HttpClientContext context = creatClientContext(host, user, password);
+
+ CloseableHttpResponse response = null;
+
+ HttpPost post = new HttpPost(uri);
+
+ String json = createBatchJson(HttpMethod.POST, opertionUri, propertyNames);
+
+ try {
+ StringEntity input = new StringEntity(json);
+ input.setContentType("application/json");
+ post.setEntity(input);
+ response = httpClient.execute(post, context);
+
+ int statusCode = response.getStatusLine().getStatusCode();
+ if (statusCode != 200) {
+ logger.error("failed to create uniqueness constraint for label [" + label + "] on properties:"
+ + propertyNames + ". request returned " + statusCode);
+ result = Neo4jOperationStatus.GENERAL_ERROR;
+ } else {
+ logger.debug("uniqueness constraint for label [ {} ] on properties {} created", label, propertyNames);
+ }
+ } catch (Exception e) {
+ logger.error("failed to create uniqueness constraint [ {} ] with properties {}, error: {}",label, propertyNames, e);
+ result = Neo4jOperationStatus.GENERAL_ERROR;
+ } finally {
+ releaseResource(response);
+ }
+
+ }
+
+ else {
+ logger.debug("no index was created for label: {} the received propertyNames list: {} is invalid", label, propertyNames);
+ return Neo4jOperationStatus.WRONG_INPUT;
+ }
+
+ return result;
+ }
+
+ public Neo4jOperationStatus deleteElement(GraphElementTypeEnum type, String label, MatchFilter filter) {
+
+ String requestJson;
+ // replace return type
+ if (type.equals(GraphElementTypeEnum.Node)) {
+ logger.debug("removing node label: {}", label);
+ requestJson = createDeleteNodeStatment(label, filter);
+
+ } else {
+ logger.error(" delete on type {} is not yet supported", type);
+ throw new RuntimeException(" delete on type " + type + " is not yet supported");
+ }
+
+ logger.debug("Try to perform request [ {} ]", requestJson);
+
+ Either<String, Neo4jOperationStatus> status = sendPostCypher(requestJson);
+ if (status.isRight()) {
+ logger.error(" delete request failed with {}", status.right());
+ return Neo4jOperationStatus.GENERAL_ERROR;
+ } else {
+ return Neo4jOperationStatus.OK;
+ }
+ }
+
+ public String getNeo4jVersion() throws Exception {
+ Map<String, Object> neo4jParams = ConfigurationManager.getConfigurationManager().getConfiguration().getNeo4j();
+ String host = (String) neo4jParams.get("host");
+ Integer port = (Integer) neo4jParams.get("port");
+ String user = (String) neo4jParams.get("user");
+ String password = (String) neo4jParams.get("password");
+
+ String uri = getServiceRoot.replace("$host$", host).replace("$port$", port.toString());
+
+ HttpClientContext context = creatClientContext(host, user, password);
+ CloseableHttpResponse response = null;
+ String result = null;
+
+ HttpGet get = new HttpGet(uri);
+ get.setHeader("Content-Type", "application/json");
+ get.setHeader("Accept", "application/json; charset=UTF-8");
+
+ try {
+ response = httpClient.execute(get, context);
+ int statusCode = response.getStatusLine().getStatusCode();
+ if (statusCode != 200) {
+ throw new Exception("Couldn't get Neo4j service root, HTTP status " + statusCode);
+ } else {
+ // Parse response
+ String responseString = new BasicResponseHandler().handleResponse(response);
+ JSONObject responseData = (JSONObject) jsonParser.parse(responseString);
+ Object obj = responseData.get("neo4j_version");
+ if (obj != null) {
+ result = (String) obj;
+ }
+ return result;
+ }
+ } finally {
+ releaseResource(response);
+ }
+ }
+
+ private String createDeleteNodeStatment(String label, MatchFilter filter) {
+ String requestJson;
+ requestJson = CypherTemplates.CypherDeleteNodeTemplate;
+
+ if (label != null && !label.isEmpty()) {
+ requestJson = requestJson.replace("$label$", label);
+ } else {
+ requestJson = requestJson.replace("$label$", "");
+ }
+
+ // replace filter
+ if (filter.getProperties().isEmpty()) {
+ // get all records by label
+ requestJson = requestJson.replace("{$filter$}", "");
+ } else {
+ String filterStr = CypherTranslator.prepareFilterBody(filter);
+ requestJson = requestJson.replace("$filter$", filterStr);
+ }
+ return requestJson;
+ }
+
+ /*
+ * removed do to fortify scan CredentialsProvider cp = new
+ * BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new
+ * UsernamePasswordCredentials(user, password)); AuthCache authCache = new
+ * BasicAuthCache(); BasicScheme basicAuth = new BasicScheme();
+ * authCache.put(new HttpHost(ip, 7474, "http"), basicAuth);
+ * context.setAuthCache(authCache); context.setCredentialsProvider(cp);
+ *
+ */
+ private HttpClientContext creatClientContext(String ip, String user, String password) {
+ HttpClientContext context = HttpClientContext.create();
+
+ return context;
+ }
+
+ private void releaseResource(CloseableHttpResponse response) {
+ if (response != null) {
+ try {
+ HttpEntity entity = response.getEntity();
+ EntityUtils.consume(entity);
+ response.close();
+ } catch (Exception e) {
+ logger.error("failed to close connection exception", e);
+ }
+ }
+ }
+
+ private String createBatchJson(HttpMethod method, String opertionUri, List<String> propertyNames) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("[ ");
+ for (int i = 0; i < propertyNames.size(); i++) {
+ sb.append("{ \"method\" : \"" + method + "\" , \"to\" : \"" + opertionUri
+ + "\" , \"body\" : { \"property_keys\" : [ \"" + propertyNames.get(i) + "\" ] } }");
+ if (i + 1 < propertyNames.size()) {
+ sb.append(",");
+ }
+ }
+ sb.append(" ]");
+ String json = sb.toString();
+ return json;
+ }
+
+ enum HttpMethod {
+ GET, PUT, POST, DELETE
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jEdge.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jEdge.java
new file mode 100644
index 0000000000..e8278a9a3e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jEdge.java
@@ -0,0 +1,69 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum;
+
+public class Neo4jEdge {
+
+ private GraphEdgeLabels edgeType;
+ private Map<String, Object> properties;
+ private ActionEnum action;
+
+ public Neo4jEdge(GraphEdgeLabels edgeType, Map<String, Object> properties, ActionEnum actionEnum) {
+ super();
+ this.edgeType = edgeType;
+ this.properties = properties;
+ this.action = actionEnum;
+ }
+
+ public GraphEdgeLabels getEdgeType() {
+ return edgeType;
+ }
+
+ public void setEdgeType(GraphEdgeLabels edgeType) {
+ this.edgeType = edgeType;
+ }
+
+ public Map<String, Object> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(Map<String, Object> properties) {
+ this.properties = properties;
+ }
+
+ public ActionEnum getAction() {
+ return action;
+ }
+
+ public void setAction(ActionEnum action) {
+ this.action = action;
+ }
+
+ @Override
+ public String toString() {
+ return "Neo4jEdge [edgeType=" + edgeType + ", properties=" + properties + ", action=" + action + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java
new file mode 100644
index 0000000000..831fb001be
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java
@@ -0,0 +1,194 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElement;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import fj.data.Either;
+
+public class Neo4jGraphBatchBuilder {
+
+ private static Logger logger = LoggerFactory.getLogger(Neo4jGraphBatchBuilder.class.getName());
+
+ public Either<BatchBuilder, Neo4jOperationStatus> buildBatchBuilderFromTable(
+ GraphNeighbourTable graphNeighbourTable) {
+
+ logger.debug("The table sent in order to build BatchBuilder is {}", graphNeighbourTable);
+
+ List<GraphNode> nodes = graphNeighbourTable.getNodes();
+ if (nodes != null && nodes.size() > 0) {
+ // String resourceId = findResourceDataIdFromNodes(nodes);
+ // if (resourceId == null || resourceId.isEmpty()) {
+ // logger.error("Cannot find resource id in the graph table");
+ // return Either.right(ActionStatus.INVALID_CONTENT);
+ // }
+ List<NodeRelation> directedEdges = graphNeighbourTable.getDirectedEdges();
+
+ List<RelationEndPoint> relationEndPoints = new ArrayList<RelationEndPoint>(nodes.size());
+ Set<Integer> nodesInRelations = findDistinctNodesIndex(directedEdges);
+
+ buildRelationEndPoints(nodes, nodesInRelations, relationEndPoints);
+
+ BatchBuilder batchBuilder = BatchBuilder.getBuilder();
+
+ for (GraphElement neo4jElement : nodes) {
+ if (neo4jElement.getAction() != ActionEnum.Delete) {
+ logger.debug("Goint to add node {} to batch builder.", neo4jElement);
+ batchBuilder.add(neo4jElement);
+ }
+ }
+
+ if (directedEdges != null) {
+ for (NodeRelation nodeRelation : directedEdges) {
+ GraphRelation relation = buildNeo4jRelation(relationEndPoints, nodeRelation);
+ logger.debug("Goint to add relation {} to catch builder.", relation);
+ batchBuilder.add(relation);
+ }
+ }
+
+ for (GraphElement neo4jElement : nodes) {
+ if (neo4jElement.getAction() == ActionEnum.Delete) {
+ logger.debug("Goint to add node {} to batch builder.", neo4jElement);
+ batchBuilder.add(neo4jElement);
+ }
+ }
+
+ return Either.left(batchBuilder);
+
+ } else {
+ logger.error("No node was sent in order to create the resource.");
+ return Either.right(Neo4jOperationStatus.BAD_REQUEST);
+ }
+ }
+
+ private Pair<String, String> getUniqueIdKeyValue(GraphNode neo4jNode) {
+
+ // String label = neo4jNode.getLabel();
+ // NodeTypeEnum nodeTypeEnum = NodeTypeEnum.getByName(label);
+ //
+ return Pair.createPair(neo4jNode.getUniqueIdKey(), neo4jNode.getUniqueId().toString());
+ }
+
+ private Set<Integer> findDistinctNodesIndex(List<NodeRelation> directedEdges) {
+
+ HashSet<Integer> nodesIndex = new HashSet<Integer>();
+
+ if (directedEdges != null) {
+ for (NodeRelation nodeRelation : directedEdges) {
+ nodesIndex.add(nodeRelation.getFromIndex());
+ nodesIndex.add(nodeRelation.getToIndex());
+ }
+ }
+
+ return nodesIndex;
+ }
+
+ private String findResourceDataIdFromNodes(List<GraphNode> nodes) {
+
+ if (nodes != null) {
+
+ for (GraphNode neo4jNode : nodes) {
+ String label = neo4jNode.getLabel();
+ if (label.equals(NodeTypeEnum.Resource.getName())) {
+ return neo4jNode.getUniqueId().toString();
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private GraphRelation buildNeo4jRelation(List<RelationEndPoint> relationEndPoints, NodeRelation nodeRelation) {
+ GraphRelation relation = new GraphRelation();
+ int fromIndex = nodeRelation.getFromIndex();
+ int toIndex = nodeRelation.getToIndex();
+ Neo4jEdge neo4jEdge = nodeRelation.getEdge();
+ relation.setFrom(relationEndPoints.get(fromIndex));
+ relation.setTo(relationEndPoints.get(toIndex));
+ relation.setType(neo4jEdge.getEdgeType().getProperty());
+
+ // TODO: fix it after change
+ Map<String, Object> edgeProps = neo4jEdge.getProperties();
+ if (edgeProps != null && false == edgeProps.isEmpty()) {
+ relation.addPropertis(edgeProps);
+ }
+
+ relation.setAction(neo4jEdge.getAction());
+ return relation;
+ }
+
+ private void buildRelationEndPoints(List<GraphNode> nodes, Set<Integer> nodesInRelations,
+ List<RelationEndPoint> relationEndPoints) {
+
+ if (nodesInRelations != null) {
+ for (Integer nodeIndex : nodesInRelations) {
+
+ GraphElement neo4jElement = nodes.get(nodeIndex);
+ GraphNode neo4jNode = (GraphNode) neo4jElement;
+ String label = neo4jNode.getLabel();
+ Pair<String, String> uniqueKeyValue = getUniqueIdKeyValue(neo4jNode);
+
+ RelationEndPoint endPoint = new RelationEndPoint(NodeTypeEnum.getByName(label), uniqueKeyValue.getKey(),
+ uniqueKeyValue.getValue());
+ relationEndPoints.add(nodeIndex, endPoint);
+
+ }
+ }
+
+ }
+
+ public static class Pair<K, V> {
+
+ private final K key;
+ private final V value;
+
+ public static <K, V> Pair<K, V> createPair(K key, V value) {
+ return new Pair<K, V>(key, value);
+ }
+
+ public Pair(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ public K getKey() {
+ return key;
+ }
+
+ public V getValue() {
+ return value;
+ }
+
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jOperationStatus.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jOperationStatus.java
new file mode 100644
index 0000000000..154449b521
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jOperationStatus.java
@@ -0,0 +1,77 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+public enum Neo4jOperationStatus {
+
+ OK, NOT_CONNECTED, NOT_AUTHORIZED, HTTP_PROTOCOL_ERROR, DB_NOT_AVAILABLE, DB_READ_ONLY, BAD_REQUEST, LEGACY_INDEX_ERROR, SCHEMA_ERROR, TRANSACTION_ERROR, EXECUTION_FAILED, ENTITY_ALREADY_EXIST,
+
+ WRONG_INPUT, GENERAL_ERROR, NOT_SUPPORTED, NOT_FOUND;
+
+ private String originError;
+ private String message;
+ private String helpErrorMsg;
+
+ private static final String NA = "NA";
+
+ Neo4jOperationStatus() {
+ originError = NA;
+ message = NA;
+ helpErrorMsg = NA;
+ }
+
+ public Neo4jOperationStatus setOriginError(String originError) {
+ this.originError = originError;
+ return this;
+ }
+
+ public Neo4jOperationStatus setMessage(String message) {
+ if (message != null && !message.isEmpty()) {
+ this.message = message;
+ }
+ return this;
+ }
+
+ public Neo4jOperationStatus setHelpErrorMsg(String helpErrorMsg) {
+ this.helpErrorMsg = helpErrorMsg;
+ return this;
+ }
+
+ public String getOriginError() {
+ return originError;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getHelpErrorMsg() {
+ return helpErrorMsg;
+ }
+
+ public String printError() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("[").append(toString()).append("-").append(originError).append("-").append(helpErrorMsg).append("-")
+ .append(message).append("]");
+ return sb.toString();
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/NodeRelation.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/NodeRelation.java
new file mode 100644
index 0000000000..c1402f402f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/NodeRelation.java
@@ -0,0 +1,65 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j;
+
+public class NodeRelation {
+
+ private int fromIndex;
+ private int toIndex;
+ private Neo4jEdge edge;
+
+ public NodeRelation(int fromIndex, int toIndex, Neo4jEdge edge) {
+ super();
+ this.fromIndex = fromIndex;
+ this.toIndex = toIndex;
+ this.edge = edge;
+ }
+
+ public int getFromIndex() {
+ return fromIndex;
+ }
+
+ public void setFromIndex(int fromIndex) {
+ this.fromIndex = fromIndex;
+ }
+
+ public int getToIndex() {
+ return toIndex;
+ }
+
+ public void setToIndex(int toIndex) {
+ this.toIndex = toIndex;
+ }
+
+ public Neo4jEdge getEdge() {
+ return edge;
+ }
+
+ public void setEdge(Neo4jEdge edge) {
+ this.edge = edge;
+ }
+
+ @Override
+ public String toString() {
+ return "NodeRelation [fromIndex=" + fromIndex + ", toIndex=" + toIndex + ", edge=" + edge + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/MatchFilter.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/MatchFilter.java
new file mode 100644
index 0000000000..10e93c1f56
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/MatchFilter.java
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j.filters;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class MatchFilter {
+ private Map<String, Object> toMatchProperties;
+
+ public MatchFilter() {
+ toMatchProperties = new HashMap<String, Object>();
+ }
+
+ public MatchFilter(Map<String, Object> toMatchProperties) {
+ super();
+ this.toMatchProperties = toMatchProperties;
+ }
+
+ public Map<String, Object> getProperties() {
+ return toMatchProperties;
+ }
+
+ public void setProperties(Map<String, Object> properties) {
+ this.toMatchProperties = properties;
+ }
+
+ public MatchFilter addToMatch(String propName, Object value) {
+ toMatchProperties.put(propName, value);
+ return this;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveByRelationFilter.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveByRelationFilter.java
new file mode 100644
index 0000000000..698077d45b
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveByRelationFilter.java
@@ -0,0 +1,81 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j.filters;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class RecursiveByRelationFilter extends RecursiveFilter {
+
+ private GraphNode node;
+ private String relationType;
+
+ public RecursiveByRelationFilter() {
+ super();
+ }
+
+ public RecursiveByRelationFilter(NodeTypeEnum nodeType, GraphNode node) {
+ super(nodeType);
+ this.node = node;
+ }
+
+ public RecursiveByRelationFilter(NodeTypeEnum nodeType) {
+ super(nodeType);
+ }
+
+ public RecursiveByRelationFilter(NodeTypeEnum nodeType, GraphNode node, String relationType) {
+ super(nodeType);
+ this.node = node;
+ this.relationType = relationType;
+ }
+
+ public RecursiveByRelationFilter addNode(GraphNode node) {
+ this.node = node;
+ return this;
+ }
+
+ public RecursiveByRelationFilter addRelation(String relationType) {
+ this.relationType = relationType;
+ return this;
+ }
+
+ public GraphNode getNode() {
+ return node;
+ }
+
+ public void setNode(GraphNode node) {
+ this.node = node;
+ }
+
+ public String getRelationType() {
+ return relationType;
+ }
+
+ public void setRelationType(String relationType) {
+ this.relationType = relationType;
+ }
+
+ @Override
+ public String toString() {
+ return "RecursiveByRelationFilter [node=" + node + ", relationType=" + relationType + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveFilter.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveFilter.java
new file mode 100644
index 0000000000..fa78539f8f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveFilter.java
@@ -0,0 +1,68 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j.filters;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class RecursiveFilter extends MatchFilter {
+
+ private List<String> childRelationTypes;
+ NodeTypeEnum nodeType;
+
+ public RecursiveFilter() {
+ childRelationTypes = new ArrayList<String>();
+ }
+
+ public RecursiveFilter(NodeTypeEnum nodeType) {
+ childRelationTypes = new ArrayList<String>();
+ this.nodeType = nodeType;
+ }
+
+ public RecursiveFilter addChildRelationType(String type) {
+ childRelationTypes.add(type);
+ return this;
+ }
+
+ public List<String> getChildRelationTypes() {
+ return childRelationTypes;
+ }
+
+ public void setChildRelationTypes(List<String> childRelationTypes) {
+ this.childRelationTypes = childRelationTypes;
+ }
+
+ public NodeTypeEnum getNodeType() {
+ return nodeType;
+ }
+
+ public void setNodeType(NodeTypeEnum nodeType) {
+ this.nodeType = nodeType;
+ }
+
+ @Override
+ public String toString() {
+ return "RecursiveFilter [childRelationTypes=" + childRelationTypes + ", nodeType=" + nodeType + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/UpdateFilter.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/UpdateFilter.java
new file mode 100644
index 0000000000..3abfdeb70e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/UpdateFilter.java
@@ -0,0 +1,56 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.neo4j.filters;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class UpdateFilter extends MatchFilter {
+
+ private Map<String, Object> toUpdate;
+
+ public UpdateFilter(Map<String, Object> toUpdate) {
+ super();
+ this.toUpdate = toUpdate;
+ }
+
+ public UpdateFilter() {
+ super();
+ toUpdate = new HashMap<String, Object>();
+ }
+
+ public UpdateFilter(Map<String, Object> toMatch, Map<String, Object> toUpdate) {
+ super(toMatch);
+ this.toUpdate = toUpdate;
+ }
+
+ public Map<String, Object> getToUpdate() {
+ return toUpdate;
+ }
+
+ public void setToUpdate(Map<String, Object> toUpdate) {
+ this.toUpdate = toUpdate;
+ }
+
+ public void addToUpdate(String property, Object value) {
+ toUpdate.put(property, value);
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/HttpRestClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/HttpRestClient.java
new file mode 100644
index 0000000000..fb09131b42
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/HttpRestClient.java
@@ -0,0 +1,403 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.rest;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map.Entry;
+import java.util.Properties;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.util.EntityUtils;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
+import org.openecomp.sdc.common.rest.api.RestResponse;
+import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpRestClient {
+
+ public final static int DEFAULT_CONNECTION_POOL_SIZE = 10;
+
+ public final static int DEFAULT_READ_TIMEOUT_IN_SEC = 30;
+
+ public final static int DEFAULT_CONNECT_TIMEOUT = 30;
+
+ public final static int DEFAULT_SOCKET_TIMEOUT = 30;
+
+ private CloseableHttpClient httpClient = null;
+
+ private PoolingHttpClientConnectionManager cm = null;
+
+ private static Logger logger = LoggerFactory.getLogger(HttpRestClient.class.getName());
+
+ private RestResponse errorRestResponse = new RestResponse("internal server error", null, 500);
+ private RestResponseAsByteArray errorRestResponseAsByteArray = new RestResponseAsByteArray(
+ "internal server error".getBytes(), null, 500);
+
+ boolean isInitialized = false;
+
+ // public static void main(String[] argv) {
+ // try {
+ // RestClientService restClientService =
+ // RestClientServiceFactory.createHttpRestClientService(new
+ // RestConfigurationInfo());
+ //
+ // String uriCreateCell =
+ // "http://172.20.37.245:9082/topology/management/cell/update";
+ // String jsonStr = " { \"cellName\" : \"mycell118\" }";
+ // String jsonUpdateStr =
+ // " { \"cellName\" : \"mycell118\", \"hostName\" : \"myhost333\" }";
+ //
+ //
+ // // jsonStr = " <note>dfd</note>";
+ //
+ // Properties headers = new Properties();
+ // headers.put("Content-type", "application/json");
+ // headers.put("Accept", "*/*");
+ //
+ // // RestResponse restResponse = restClientService.doPOST(uriCreateCell,
+ // headers, jsonStr);
+ //
+ // RestResponse restResponse = restClientService.doPUT(uriCreateCell,
+ // headers, jsonUpdateStr);
+ //
+ // System.out.println(restResponse);
+ //
+ //
+ // } catch (RestClientServiceExeption e) {
+ // // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // }
+ //
+ // }
+
+ public HttpRestClient() {
+ super();
+ isInitialized = init(new RestConfigurationInfo());
+ }
+
+ public HttpRestClient(RestConfigurationInfo restConfigurationInfo) {
+ super();
+ isInitialized = init(restConfigurationInfo);
+ }
+
+ public boolean init(RestConfigurationInfo restConfigurationInfo) {
+
+ logger.debug("create HttpRestClient: restConfigurationInfo={}", restConfigurationInfo);
+ boolean result = false;
+ // try {
+ createHttpClient(restConfigurationInfo);
+ result = true;
+ // } catch (KeyManagementException e) {
+ // String msg = "Failed creating client config for rest. "
+ // + e.getMessage();
+ // logger.debug(msg, e);
+ // //TODO: log. error
+ // } catch (NoSuchAlgorithmException e) {
+ // String msg = "Failed creating client config for rest. "
+ // + e.getMessage();
+ // logger.debug(msg, e);
+ // //TODO: log. error
+ // }
+
+ logger.debug("Finish creating HttpRestClient. Result is {}", result);
+ return result;
+ }
+
+ public void destroy() {
+
+ try {
+ httpClient.close();
+ logger.debug("Http client closed");
+ } catch (Exception e) {
+ logger.trace("Failed to close http client", e);
+ }
+
+ }
+
+ private void createHttpClient(RestConfigurationInfo restConfigurationInfo) {
+ // throws KeyManagementException, NoSuchAlgorithmException {
+
+ PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
+
+ int connPoolSize = getConnectionPoolSize(restConfigurationInfo);
+ connManager.setMaxTotal(connPoolSize);
+ connManager.setDefaultMaxPerRoute(10);
+ connManager.setValidateAfterInactivity(15000);
+
+ // Create common default configuration
+ int socketTimeout = getTimeout(restConfigurationInfo.getSocketTimeoutInSec(), DEFAULT_SOCKET_TIMEOUT);
+
+ int connectTimeoutInSec = getTimeout(restConfigurationInfo.getConnectTimeoutInSec(), DEFAULT_CONNECT_TIMEOUT);
+
+ int readTimeOut = getTimeout(restConfigurationInfo.getReadTimeoutInSec(), DEFAULT_READ_TIMEOUT_IN_SEC);
+
+ RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(connectTimeoutInSec)
+ .setSocketTimeout(socketTimeout).setConnectionRequestTimeout(readTimeOut).build();
+
+ this.cm = connManager;
+
+ this.httpClient = HttpClients.custom().setDefaultRequestConfig(clientConfig).setConnectionManager(connManager)
+ .build();
+
+ }
+
+ private int getConnectionPoolSize(RestConfigurationInfo restConfigurationInfo) {
+ Integer connPoolSizeObj = restConfigurationInfo.getConnectionPoolSize();
+ int connPoolSize = DEFAULT_CONNECTION_POOL_SIZE;
+ if (connPoolSizeObj != null) {
+ connPoolSize = connPoolSizeObj.intValue();
+ if (connPoolSize <= 0) {
+ connPoolSize = DEFAULT_CONNECTION_POOL_SIZE;
+ }
+ }
+ return connPoolSize;
+ }
+
+ private int getTimeout(Integer value, Integer defaultValue) {
+
+ int defaultTimeout = defaultValue != null ? defaultValue.intValue() * 1000 : 0;
+
+ int timeout = defaultTimeout;
+
+ if (value != null) {
+ timeout = defaultValue.intValue() * 1000;
+ if (timeout <= 0) {
+ timeout = defaultTimeout;
+ }
+ }
+
+ return timeout;
+ }
+
+ /**
+ * Executes RS-GET to perform FIND.
+ *
+ * @param headerParameterKey
+ * String
+ * @param headerParameterValue
+ * String
+ * @return String
+ */
+ public RestResponse doGET(String uri, Properties headers) {
+
+ logger.debug("Before executing uri {}. headers = {}", uri, headers);
+
+ HttpGet httpGet = new HttpGet(uri);
+
+ RestResponse response = execute(httpGet, headers);
+
+ return response;
+ }
+
+ public RestResponse doPUT(String uri, Properties headers, String body) {
+
+ logger.debug("Before executing uri {}. headers = {}. body = ", uri, headers, body);
+
+ HttpPut httpPut = new HttpPut(uri);
+ StringEntity data = new StringEntity(body, ContentType.APPLICATION_JSON);
+ httpPut.setEntity(data);
+ RestResponse response = execute(httpPut, headers);
+
+ return response;
+ }
+
+ public RestResponse doPOST(String uri, Properties headers, String body) {
+
+ logger.debug("Before executing uri {}. headers = {}. body = {}", uri, headers, body);
+
+ HttpPost httpPost = new HttpPost(uri);
+ StringEntity data = new StringEntity(body, ContentType.APPLICATION_JSON);
+ httpPost.setEntity(data);
+ RestResponse response = execute(httpPost, headers);
+
+ return response;
+ }
+
+ public RestResponseAsByteArray doGetAsByteArray(String uri, Properties headers) {
+
+ logger.debug("Before executing uri {}. headers = {}.", uri, headers);
+
+ HttpGet httpGet = new HttpGet(uri);
+
+ RestResponseAsByteArray response = executeAndReturnByteArray(httpGet, headers);
+
+ return response;
+ }
+
+ private void addHeadersToRequest(HttpRequestBase httpRequestBase, Properties headers) {
+
+ if (headers != null) {
+ for (Entry<Object, Object> entry : headers.entrySet()) {
+ httpRequestBase.addHeader(entry.getKey().toString(), entry.getValue().toString());
+ }
+ }
+
+ }
+
+ private RestResponse execute(HttpRequestBase httpRequestBase, Properties headers) {
+
+ RestResponse restResponse = null;
+
+ CloseableHttpResponse httpResponse = null;
+
+ try {
+
+ addHeadersToRequest(httpRequestBase, headers);
+
+ httpResponse = this.httpClient.execute(httpRequestBase);
+
+ restResponse = buildRestResponseFromResult(httpResponse);
+
+ logger.debug("After executing uri {}. response = {}.", httpRequestBase.getURI().toString(), restResponse);
+ } catch (Exception exception) {
+ httpRequestBase.abort();
+
+ String description = "Failed executing http request " + httpRequestBase.getURI().toString() + "("
+ + httpRequestBase.getMethod() + ")";
+ BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description,
+ ErrorSeverity.ERROR);
+ restResponse = errorRestResponse;
+ } finally {
+ // ensure the connection gets released to the manager
+ releaseResource(httpResponse);
+ }
+
+ return restResponse;
+ }
+
+ private RestResponse buildRestResponseFromResult(CloseableHttpResponse httpResponse) throws IOException {
+
+ int statusCode = httpResponse.getStatusLine().getStatusCode();
+ String statusDesc = httpResponse.getStatusLine().getReasonPhrase();
+
+ HttpEntity entity = httpResponse.getEntity();
+ String response = null;
+ if (entity != null) {
+ response = EntityUtils.toString(entity);
+ }
+
+ RestResponse restResponse = new RestResponse(response, statusDesc, statusCode);
+
+ return restResponse;
+ }
+
+ private RestResponseAsByteArray buildRestResponseByteArrayFromResult(CloseableHttpResponse httpResponse)
+ throws IOException {
+
+ int statusCode = httpResponse.getStatusLine().getStatusCode();
+ String statusDesc = httpResponse.getStatusLine().getReasonPhrase();
+
+ HttpEntity entity = httpResponse.getEntity();
+
+ byte[] response = null;
+ if (entity != null) {
+ InputStream content = entity.getContent();
+ if (content != null) {
+ response = IOUtils.toByteArray(content);
+ }
+ }
+
+ RestResponseAsByteArray restResponse = new RestResponseAsByteArray(response, statusDesc, statusCode);
+
+ return restResponse;
+ }
+
+ private RestResponseAsByteArray executeAndReturnByteArray(HttpRequestBase httpRequestBase, Properties headers) {
+
+ RestResponseAsByteArray restResponse = null;
+
+ CloseableHttpResponse httpResponse = null;
+
+ try {
+
+ addHeadersToRequest(httpRequestBase, headers);
+
+ httpResponse = this.httpClient.execute(httpRequestBase);
+
+ restResponse = buildRestResponseByteArrayFromResult(httpResponse);
+
+ if (restResponse != null) {
+ logger.debug("After executing uri {}. Response: {}.", httpRequestBase.getURI().toString(), restResponse.toPrettyString());
+ }
+
+ } catch (Exception exception) {
+ httpRequestBase.abort();
+ String description = "Failed executing http request " + httpRequestBase.getURI().toString() + "("
+ + httpRequestBase.getMethod() + ")";
+ BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description,
+ ErrorSeverity.ERROR);
+ logger.debug(description, exception);
+ restResponse = errorRestResponseAsByteArray;
+ } finally {
+ // ensure the connection gets released to the manager
+ releaseResource(httpResponse);
+ }
+
+ return restResponse;
+ }
+
+ /**
+ * This method print the JSON response from the REST Server
+ *
+ * @param response
+ * the JSON response from the REST server
+ * @param method
+ * name of method
+ */
+ private void logResponse(String response, String method) {
+ logger.trace(method + " response = " + response);
+ }
+
+ private void releaseResource(CloseableHttpResponse response) {
+ if (response != null) {
+ try {
+ HttpEntity entity = response.getEntity();
+ if (entity != null) {
+ EntityUtils.consume(entity);
+ }
+ response.close();
+ } catch (Exception e) {
+ logger.error("failed to close connection exception", e);
+ }
+ }
+ }
+
+ public boolean isInitialized() {
+ return isInitialized;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfo.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfo.java
new file mode 100644
index 0000000000..1e45ba6ae3
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfo.java
@@ -0,0 +1,110 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.rest;
+
+public class RestConfigurationInfo {
+
+ private Integer readTimeoutInSec = null;
+
+ private Boolean ignoreCertificate = null;
+
+ private Integer connectionPoolSize = null;
+
+ private Integer connectTimeoutInSec = null;
+
+ private Integer socketTimeoutInSec = null;
+
+ /**
+ * @return the readTimeoutInSec
+ */
+ public Integer getReadTimeoutInSec() {
+ return readTimeoutInSec;
+ }
+
+ /**
+ * @param readTimeoutInSec
+ * the readTimeoutInSec to set
+ */
+ public void setReadTimeoutInSec(Integer readTimeoutInSec) {
+ this.readTimeoutInSec = readTimeoutInSec;
+ }
+
+ /**
+ * @return the ignoreCertificate
+ */
+ public Boolean getIgnoreCertificate() {
+ return ignoreCertificate;
+ }
+
+ /**
+ * @param ignoreCertificate
+ * the ignoreCertificate to set
+ */
+ public void setIgnoreCertificate(Boolean ignoreCertificate) {
+ this.ignoreCertificate = ignoreCertificate;
+ }
+
+ /**
+ * @return the connectionPoolSize
+ */
+ public Integer getConnectionPoolSize() {
+ return connectionPoolSize;
+ }
+
+ /**
+ * @param connectionPoolSize
+ * the connectionPoolSize to set
+ */
+ public void setConnectionPoolSize(Integer connectionPoolSize) {
+ this.connectionPoolSize = connectionPoolSize;
+ }
+
+ /**
+ * @return the connectTimeoutInSec
+ */
+ public Integer getConnectTimeoutInSec() {
+ return connectTimeoutInSec;
+ }
+
+ /**
+ * @param connectTimeoutInSec
+ * the connectTimeoutInSec to set
+ */
+ public void setConnectTimeoutInSec(Integer connectTimeoutInSec) {
+ this.connectTimeoutInSec = connectTimeoutInSec;
+ }
+
+ public Integer getSocketTimeoutInSec() {
+ return socketTimeoutInSec;
+ }
+
+ public void setSocketTimeoutInSec(Integer socketTimeoutInSec) {
+ this.socketTimeoutInSec = socketTimeoutInSec;
+ }
+
+ @Override
+ public String toString() {
+ return "RestConfigurationInfo [readTimeoutInSec=" + readTimeoutInSec + ", ignoreCertificate="
+ + ignoreCertificate + ", connectionPoolSize=" + connectionPoolSize + ", connectTimeoutInSec="
+ + connectTimeoutInSec + ", socketTimeoutInSec=" + socketTimeoutInSec + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/QueryType.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/QueryType.java
new file mode 100644
index 0000000000..689ed32a8a
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/QueryType.java
@@ -0,0 +1,28 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.titan;
+
+/**
+ * Created by mlando on 9/21/2016.
+ */
+public enum QueryType {
+ HAS, HAS_NOT
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java
new file mode 100644
index 0000000000..535146d692
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java
@@ -0,0 +1,1848 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.titan;
+
+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 javax.annotation.Resource;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.ImmutableTriple;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Element;
+import org.apache.tinkerpop.gremlin.structure.Property;
+import org.apache.tinkerpop.gremlin.structure.T;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+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.GraphNode;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.resources.data.GraphNodeLock;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import com.thinkaurelius.titan.core.PropertyKey;
+import com.thinkaurelius.titan.core.TitanEdge;
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanGraphQuery;
+import com.thinkaurelius.titan.core.TitanVertex;
+import com.thinkaurelius.titan.core.TitanVertexQuery;
+import com.thinkaurelius.titan.graphdb.query.TitanPredicate;
+
+import fj.data.Either;
+
+@Component("titan-generic-dao")
+public class TitanGenericDao {
+
+ @Resource
+ TitanGraphClient titanClient;
+
+ private static Logger logger = LoggerFactory.getLogger(TitanGenericDao.class.getName());
+ private static final String LOCK_NODE_PREFIX = "lock_";
+
+ public TitanGenericDao() {
+ logger.info("** TitanGenericDao created");
+ }
+
+ public TitanOperationStatus commit() {
+ logger.debug("doing commit.");
+ return titanClient.commit();
+ }
+
+ public TitanOperationStatus rollback() {
+ return titanClient.rollback();
+ }
+
+ public Either<TitanGraph, TitanOperationStatus> getGraph() {
+ return titanClient.getGraph();
+ }
+
+ // For healthCheck
+ public boolean isGraphOpen() {
+ return titanClient.getHealth();
+ }
+
+ /**
+ *
+ * @param node
+ * @param clazz
+ * @return
+ */
+ public <T extends GraphNode> Either<T, TitanOperationStatus> createNode(T node, Class<T> clazz) {
+ logger.debug("try to create node for ID [{}]", node.getKeyValueId());
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ T newNode;
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ Vertex vertex = tGraph.addVertex();
+
+ vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), node.getLabel());
+
+ Map<String, Object> properties = node.toGraphMap();
+ if (properties != null) {
+ setProperties(vertex, properties);
+ }
+ Map<String, Object> newProps = getProperties(vertex);
+ newNode = GraphElementFactory.createElement(node.getLabel(), GraphElementTypeEnum.Node, newProps, clazz);
+ logger.debug("created node for props : {}", newProps);
+ logger.debug("Node was created for ID [{}]", node.getKeyValueId());
+ return Either.left(newNode);
+
+ } catch (Exception e) {
+ logger.debug("Failed to create Node for ID [{}]", node.getKeyValueId(), e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ logger.debug("Failed to create Node for ID [{}] {}", node.getKeyValueId(), graph.right().value());
+ return Either.right(graph.right().value());
+ }
+ }
+
+ public Either<TitanVertex, TitanOperationStatus> createNode(GraphNode node) {
+ logger.debug("try to create node for ID [{}]", node.getKeyValueId());
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ TitanVertex vertex = tGraph.addVertex();
+
+ vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), node.getLabel());
+
+ Map<String, Object> properties = node.toGraphMap();
+ if (properties != null) {
+ setProperties(vertex, properties);
+ }
+ logger.debug("Node was created for ID [{}]", node.getKeyValueId());
+ return Either.left(vertex);
+
+ } catch (Exception e) {
+ logger.debug("Failed to create Node for ID [{}]", node.getKeyValueId(), e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ logger.debug("Failed to create Node for ID [{}] {}", node.getKeyValueId(), graph.right().value());
+ return Either.right(graph.right().value());
+ }
+ }
+
+ /**
+ *
+ * @param relation
+ * @return
+ */
+ public Either<GraphRelation, TitanOperationStatus> createRelation(GraphRelation relation) {
+ logger.debug("try to create relation from [{}] to [{}] ", relation.getFrom(), relation.getTo());
+
+ RelationEndPoint from = relation.getFrom();
+ RelationEndPoint to = relation.getTo();
+ ImmutablePair<String, Object> fromKeyId = new ImmutablePair<String, Object>(from.getIdName(), from.getIdValue());
+ ImmutablePair<String, Object> toKeyId = new ImmutablePair<String, Object>(to.getIdName(), to.getIdValue());
+
+ return createEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName(), relation.toGraphMap());
+
+ }
+
+ private Either<GraphRelation, TitanOperationStatus> createEdge(String type, ImmutablePair<String, Object> from, ImmutablePair<String, Object> to, String fromLabel, String toLabel, Map<String, Object> properties) {
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+
+ if (graph.isLeft()) {
+ try {
+ Either<Vertex, TitanOperationStatus> fromV = getVertexByPropertyAndLabel(from.getKey(), from.getValue(), fromLabel);
+ if (fromV.isRight()) {
+ TitanOperationStatus error = fromV.right().value();
+ if (TitanOperationStatus.NOT_FOUND.equals(error)) {
+ return Either.right(TitanOperationStatus.INVALID_ID);
+ } else {
+ return Either.right(error);
+ }
+ }
+ Either<Vertex, TitanOperationStatus> toV = getVertexByPropertyAndLabel(to.getKey(), to.getValue(), toLabel);
+ if (toV.isRight()) {
+ TitanOperationStatus error = toV.right().value();
+ if (TitanOperationStatus.NOT_FOUND.equals(error)) {
+ return Either.right(TitanOperationStatus.INVALID_ID);
+ } else {
+ return Either.right(error);
+ }
+ }
+
+ Vertex fromVertex = fromV.left().value();
+ Vertex toVertex = toV.left().value();
+ Edge edge = fromVertex.addEdge(type, toVertex);
+
+ if (properties != null) {
+
+ setProperties(edge, properties);
+ }
+
+ Vertex vertexOut = edge.outVertex();
+ Vertex vertexIn = edge.inVertex();
+
+ GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class);
+ GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class);
+
+ GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn);
+
+ return Either.left(newRelation);
+ } catch (Exception e) {
+ logger.debug("Failed to create edge from [{}] to [{}]", from, to, e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ } else {
+ logger.debug("Failed to create edge from [{}] to [{}] {}", from, to, graph.right().value());
+ return Either.right(graph.right().value());
+ }
+ }
+
+ public TitanOperationStatus createEdge(TitanVertex vertexOut, TitanVertex vertexIn, GraphEdgeLabels type, Map<String, Object> properties) {
+ try {
+ Edge edge = vertexOut.addEdge(type.getProperty(), vertexIn);
+
+ if (properties != null) {
+
+ setProperties(edge, properties);
+ }
+ } catch (Exception e) {
+ logger.debug("Failed to create edge from [{}] to [{}]", vertexOut, vertexIn, e);
+ return TitanGraphClient.handleTitanException(e);
+ }
+ return TitanOperationStatus.OK;
+
+ }
+
+ public TitanOperationStatus createEdge(TitanVertex vertexOut, GraphNode to, GraphEdgeLabels type, Map<String, Object> properties) {
+
+ TitanVertex vertexIn;
+ Either<Vertex, TitanOperationStatus> toV = getVertexByPropertyAndLabel(to.getUniqueIdKey(), to.getUniqueId(), to.getLabel());
+ if (toV.isRight()) {
+ TitanOperationStatus error = toV.right().value();
+ if (TitanOperationStatus.NOT_FOUND.equals(error)) {
+ return TitanOperationStatus.INVALID_ID;
+ } else {
+ return error;
+ }
+ }
+ vertexIn = (TitanVertex) toV.left().value();
+ return createEdge(vertexOut, vertexIn, type, properties);
+ }
+
+ /**
+ *
+ * @param from
+ * @param to
+ * @param label
+ * @param properties
+ * @return
+ */
+ public Either<GraphRelation, TitanOperationStatus> createRelation(GraphNode from, GraphNode to, GraphEdgeLabels label, Map<String, Object> properties) {
+ logger.debug("try to create relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId());
+ return createEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel(), properties);
+ }
+
+ public Either<GraphRelation, TitanOperationStatus> replaceRelationLabel(GraphNode from, GraphNode to, GraphEdgeLabels label, GraphEdgeLabels newLabel) {
+
+ logger.debug("try to replace relation {} to {} from [{}] to [{}]", label.name(), newLabel.name(), from.getKeyValueId(), to.getKeyValueId());
+ Either<GraphRelation, TitanOperationStatus> getRelationResult = getRelation(from, to, label);
+ if (getRelationResult.isRight()) {
+ return getRelationResult;
+ }
+
+ GraphRelation origRelation = getRelationResult.left().value();
+ Either<GraphRelation, TitanOperationStatus> createRelationResult = createRelation(from, to, newLabel, origRelation.toGraphMap());
+ if (createRelationResult.isRight()) {
+ return createRelationResult;
+ }
+
+ Either<GraphRelation, TitanOperationStatus> deleteRelationResult = deleteRelation(origRelation);
+ if (deleteRelationResult.isRight()) {
+ return deleteRelationResult;
+ }
+ return Either.left(createRelationResult.left().value());
+ }
+
+ /**
+ *
+ * @param keyName
+ * @param keyValue
+ * @param clazz
+ * @return
+ */
+ public <T extends GraphNode> Either<T, TitanOperationStatus> getNode(String keyName, Object keyValue, Class<T> clazz) {
+
+ logger.debug("Try to get node for key [{}] with value [{}] ", keyName, keyValue);
+
+ Either<TitanVertex, TitanOperationStatus> vertexByProperty = getVertexByProperty(keyName, keyValue);
+
+ if (vertexByProperty.isLeft()) {
+ try {
+ Vertex vertex = vertexByProperty.left().value();
+ Map<String, Object> properties = getProperties(vertex);
+ T node = GraphElementFactory.createElement((String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()), GraphElementTypeEnum.Node, properties, clazz);
+ return Either.left(node);
+ } catch (Exception e) {
+ logger.debug("Failed to get node for key [{}] with value [{}] ", keyName, keyValue, e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ } else {
+ logger.debug("Failed to get node for key [{}] with value [{}] ", keyName, keyValue, vertexByProperty.right().value());
+ return Either.right(vertexByProperty.right().value());
+ }
+ }
+
+ /**
+ *
+ * @param from
+ * @param to
+ * @param label
+ * @return
+ */
+ public Either<GraphRelation, TitanOperationStatus> getRelation(GraphNode from, GraphNode to, GraphEdgeLabels label) {
+ logger.debug("try to get relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId());
+
+ ImmutablePair<String, Object> keyValueIdFrom = from.getKeyValueId();
+ ImmutablePair<String, Object> keyValueIdTo = to.getKeyValueId();
+
+ Either<Edge, TitanOperationStatus> edge = getEdgeByVerticies(keyValueIdFrom.getKey(), keyValueIdFrom.getValue(), keyValueIdTo.getKey(), keyValueIdTo.getValue(), label.getProperty());
+
+ if (edge.isLeft()) {
+ try {
+ Map<String, Object> properties = getProperties(edge.left().value());
+ GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, from, to);
+ return Either.left(relation);
+ } catch (Exception e) {
+ logger.debug("Failed to get get relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId(), e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ } else {
+ logger.debug("Failed to get get relation from [{}] to [{}] {}", from.getKeyValueId(), to.getKeyValueId(), edge.right().value());
+ return Either.right(edge.right().value());
+ }
+ }
+
+ public Either<GraphRelation, TitanOperationStatus> deleteIncomingRelationByCriteria(GraphNode to, GraphEdgeLabels label, Map<String, Object> props) {
+
+ Either<Edge, TitanOperationStatus> edgeByCriteria = getIncomingEdgeByCriteria(to, label, props);
+ if (edgeByCriteria.isLeft()) {
+ Either<TitanGraph, TitanOperationStatus> graph = getGraph();
+ if (graph.isLeft()) {
+ Edge edge = edgeByCriteria.left().value();
+ logger.debug("delete edge {} to {} ", label.getProperty(), to.getUniqueId());
+ edge.remove();
+ Map<String, Object> properties = getProperties(edge);
+ Vertex fromVertex = edge.outVertex();
+ String fromLabel = fromVertex.value(GraphPropertiesDictionary.LABEL.getProperty());
+ GraphNode nodeFrom = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(fromVertex), GraphNode.class);
+ GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, nodeFrom, to);
+ return Either.left(relation);
+ } else {
+ logger.debug("failed to get graph");
+ return Either.right(graph.right().value());
+ }
+
+ } else {
+ logger.debug("failed to find edge {} to {}", label.getProperty(), to.getUniqueId());
+ return Either.right(edgeByCriteria.right().value());
+ }
+
+ }
+
+ public Either<GraphRelation, TitanOperationStatus> getIncomingRelationByCriteria(GraphNode to, GraphEdgeLabels label, Map<String, Object> props) {
+
+ Either<Edge, TitanOperationStatus> edgeByCriteria = getIncomingEdgeByCriteria(to, label, props);
+ if (edgeByCriteria.isLeft()) {
+ Either<TitanGraph, TitanOperationStatus> graph = getGraph();
+ if (graph.isLeft()) {
+ Edge edge = edgeByCriteria.left().value();
+ Map<String, Object> properties = getProperties(edge);
+ Vertex fromVertex = edge.outVertex();
+ String fromLabel = fromVertex.value(GraphPropertiesDictionary.LABEL.getProperty());
+ GraphNode nodeFrom = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(fromVertex), GraphNode.class);
+ GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, nodeFrom, to);
+ return Either.left(relation);
+ } else {
+ logger.debug("failed to get graph");
+ return Either.right(graph.right().value());
+ }
+
+ } else {
+ logger.debug("failed to find edge {} to {}", label.getProperty(), to.getUniqueId());
+ return Either.right(edgeByCriteria.right().value());
+ }
+
+ }
+
+ public Either<Edge, TitanOperationStatus> getIncomingEdgeByCriteria(GraphNode to, GraphEdgeLabels label, Map<String, Object> props) {
+
+ ImmutablePair<String, Object> keyValueIdTo = to.getKeyValueId();
+
+ Either<TitanVertex, TitanOperationStatus> vertexFrom = getVertexByProperty(keyValueIdTo.getKey(), keyValueIdTo.getValue());
+ if (vertexFrom.isRight()) {
+ return Either.right(vertexFrom.right().value());
+ }
+ Vertex vertex = vertexFrom.left().value();
+ TitanVertex titanVertex = (TitanVertex) vertex;
+ TitanVertexQuery<?> query = titanVertex.query();
+ query = query.labels(label.getProperty());
+
+ if (props != null && !props.isEmpty()) {
+ for (Map.Entry<String, Object> entry : props.entrySet()) {
+ query = query.has(entry.getKey(), entry.getValue());
+ }
+ }
+ Edge matchingEdge = null;
+ Iterable<TitanEdge> edges = query.edges();
+ if (edges == null) {
+ logger.debug("No edges in graph for criteria");
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ Iterator<TitanEdge> eIter = edges.iterator();
+ if (eIter.hasNext()) {
+ TitanEdge edge = eIter.next();
+ matchingEdge = edge;
+ }
+
+ if (matchingEdge == null) {
+ logger.debug("No edges in graph for criteria");
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ return Either.left(matchingEdge);
+ }
+
+ private Either<Edge, TitanOperationStatus> getEdgeByVerticies(String keyNameFrom, Object keyValueFrom, String keyNameTo, Object keyValueTo, String label) {
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+
+ if (graph.isLeft()) {
+ try {
+ Either<TitanVertex, TitanOperationStatus> vertexFrom = getVertexByProperty(keyNameFrom, keyValueFrom);
+ if (vertexFrom.isRight()) {
+ return Either.right(vertexFrom.right().value());
+ }
+ Iterable<TitanEdge> edges = ((TitanVertex) vertexFrom.left().value()).query().labels(label).edges();
+ Iterator<TitanEdge> eIter = edges.iterator();
+ while (eIter.hasNext()) {
+ Edge edge = eIter.next();
+ Vertex vertexIn = edge.inVertex();
+ if (vertexIn.value(keyNameTo) != null && vertexIn.value(keyNameTo).equals(keyValueTo) && label.equals(edge.label())) {
+ return Either.left(edge);
+ }
+ }
+ logger.debug("No relation in graph from [{}={}] to [{}={}]", keyNameFrom, keyValueFrom, keyNameTo, keyValueTo);
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ } catch (Exception e) {
+ logger.debug("Failed to get get relation from [{}={}] to [{}={}]", keyNameFrom, keyValueFrom, keyNameTo, keyValueTo, e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ } else {
+ return Either.right(graph.right().value());
+ }
+ }
+
+ public Either<List<Edge>, TitanOperationStatus> getEdgesForNode(GraphNode node, Direction requestedDirection) {
+
+ Either<List<Edge>, TitanOperationStatus> result;
+
+ ImmutablePair<String, Object> keyValueId = node.getKeyValueId();
+ Either<TitanVertex, TitanOperationStatus> eitherVertex = getVertexByProperty(keyValueId.getKey(), keyValueId.getValue());
+
+ if (eitherVertex.isLeft()) {
+ List<Edge> edges = prepareEdgesList(eitherVertex.left().value(), requestedDirection);
+
+ result = Either.left(edges);
+ } else {
+ result = Either.right(eitherVertex.right().value());
+ }
+ return result;
+ }
+
+ private List<Edge> prepareEdgesList(Vertex vertex, Direction requestedDirection) {
+ List<Edge> edges = new ArrayList<>();
+ Iterator<TitanEdge> edgesItr = ((TitanVertex) vertex).query().edges().iterator();
+ while (edgesItr.hasNext()) {
+ Edge edge = edgesItr.next();
+ Direction currEdgeDirection = getEdgeDirection(vertex, edge);
+ if (currEdgeDirection == requestedDirection || requestedDirection == Direction.BOTH) {
+ edges.add(edge);
+ }
+
+ }
+ return edges;
+ }
+
+ private Direction getEdgeDirection(Vertex vertex, Edge edge) {
+ Direction result;
+ Vertex vertexOut = edge.outVertex();
+ if (vertexOut.equals(vertex)) {
+ result = Direction.OUT;
+ } else {
+ result = Direction.IN;
+
+ }
+ return result;
+ }
+
+ /**
+ *
+ * @param from
+ * @param to
+ * @param label
+ * @param properties
+ * @return
+ */
+ public Either<GraphRelation, TitanOperationStatus> updateRelation(GraphNode from, GraphNode to, GraphEdgeLabels label, Map<String, Object> properties) {
+ logger.debug("try to update relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId());
+ return updateEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel(), properties);
+ }
+
+ private Either<GraphRelation, TitanOperationStatus> updateEdge(String type, ImmutablePair<String, Object> from, ImmutablePair<String, Object> to, String fromLabel, String toLabel, Map<String, Object> properties) {
+
+ Either<Edge, TitanOperationStatus> edgeS = getEdgeByVerticies(from.getKey(), from.getValue(), to.getKey(), to.getValue(), type);
+ if (edgeS.isLeft()) {
+
+ try {
+ Edge edge = edgeS.left().value();
+ if (properties != null) {
+ setProperties(edge, properties);
+ }
+
+ Vertex vertexOut = edge.outVertex();
+ Vertex vertexIn = edge.inVertex();
+
+ GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class);
+ GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class);
+
+ GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn);
+ if (logger.isDebugEnabled()) {
+ logger.debug("Relation was updated from [ {} ] to [ {} ]", from, to);
+ }
+ return Either.left(newRelation);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to update relation from [ {} ] [ {} ] {}", from, to, e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to update relation from [ {} ] [ {} ] {}", from, to, edgeS.right().value());
+ }
+ return Either.right(edgeS.right().value());
+ }
+ }
+
+ /**
+ *
+ * @param relation
+ * @return
+ */
+ public Either<GraphRelation, TitanOperationStatus> updateRelation(GraphRelation relation) {
+ logger.debug("try to update relation from [{}] to [{}]", relation.getFrom(), relation.getTo());
+ RelationEndPoint from = relation.getFrom();
+ RelationEndPoint to = relation.getTo();
+ ImmutablePair<String, Object> fromKeyId = new ImmutablePair<String, Object>(from.getIdName(), from.getIdValue());
+ ImmutablePair<String, Object> toKeyId = new ImmutablePair<String, Object>(to.getIdName(), to.getIdValue());
+
+ return updateEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName(), relation.toGraphMap());
+
+ }
+
+ private Either<Vertex, TitanOperationStatus> getVertexByPropertyAndLabel(String name, Object value, String label) {
+
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ @SuppressWarnings("unchecked")
+ Iterable<TitanVertex> vertecies = tGraph.query().has(name, value).has(GraphPropertiesDictionary.LABEL.getProperty(), label).vertices();
+
+ java.util.Iterator<TitanVertex> iterator = vertecies.iterator();
+ if (iterator.hasNext()) {
+ Vertex vertex = iterator.next();
+ return Either.left(vertex);
+ }
+ if (logger.isDebugEnabled()) {
+ logger.debug("No vertex in graph for key = {} and value = {} label = {}", name, value, label);
+ }
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to get vertex in graph for key = {} and value = {} label = {}", name, value, label);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("No vertex in graph for key = {} and value = {} label = {}. error : {}", name, value, label, graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ }
+
+ public Either<TitanVertex, TitanOperationStatus> getVertexByProperty(String name, Object value) {
+
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (value == null) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("No vertex in graph for key = {} and value = {}", name, value);
+ }
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ @SuppressWarnings("unchecked")
+ Iterable<TitanVertex> vertecies = tGraph.query().has(name, value).vertices();
+
+ java.util.Iterator<TitanVertex> iterator = vertecies.iterator();
+ if (iterator.hasNext()) {
+ TitanVertex vertex = iterator.next();
+ return Either.left(vertex);
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("No vertex in graph for key ={} and value = {}", name, value);
+ }
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to get vertex in graph for key = {} and value = ", name, value);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("No vertex in graph for key = {} and value = {} error : {}", name, value, graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ }
+
+ public <T extends GraphNode> Either<List<T>, TitanOperationStatus> getByCriteria(NodeTypeEnum type, Map<String, Object> hasProps, Map<String, Object> hasNotProps, Class<T> clazz) {
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
+ query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName());
+
+ if (hasProps != null && !hasProps.isEmpty()) {
+ for (Map.Entry<String, Object> entry : hasProps.entrySet()) {
+ query = query.has(entry.getKey(), entry.getValue());
+ }
+ }
+ if (hasNotProps != null && !hasNotProps.isEmpty()) {
+ for (Map.Entry<String, Object> entry : hasNotProps.entrySet()) {
+ query = query.hasNot(entry.getKey(), entry.getValue());
+ }
+ }
+ Iterable<TitanVertex> vertices = query.vertices();
+ if (vertices == null) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ List<T> result = new ArrayList<T>();
+
+ while (iterator.hasNext()) {
+ Vertex vertex = iterator.next();
+
+ Map<String, Object> newProp = getProperties(vertex);
+
+ T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz);
+ result.add(element);
+ }
+ if (logger.isDebugEnabled()) {
+ logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties has = {}, properties hasNot = {} is {}", type, hasProps, hasNotProps, result.size());
+ }
+ if (result.size() == 0) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ return Either.left(result);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type = {}", type, e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type ={} error : {}", type, graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ }
+
+ public <T extends GraphNode> Either<List<T>, TitanOperationStatus> getByCriteria(NodeTypeEnum type, Class<T> clazz, List<ImmutableTriple<QueryType, String, Object>> props) {
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
+ query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName());
+ for (ImmutableTriple<QueryType, String, Object> prop : props) {
+ if (QueryType.HAS.equals(prop.getLeft())) {
+ query = query.has(prop.getMiddle(), prop.getRight());
+ } else {
+ query = query.hasNot(prop.getMiddle(), prop.getRight());
+ }
+ }
+ Iterable<TitanVertex> vertices = query.vertices();
+ if (vertices == null) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ List<T> result = new ArrayList<T>();
+
+ while (iterator.hasNext()) {
+ Vertex vertex = iterator.next();
+
+ Map<String, Object> newProp = getProperties(vertex);
+
+ T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz);
+ result.add(element);
+ }
+ if (result.size() == 0) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ return Either.left(result);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type = {}", type, e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type ={} error : {}", type, graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ }
+
+ private boolean vertexLeftNotContainsAllRightProps(Map<String, Object> leftProps, Map<String, Object> rightProps) {
+
+ if (rightProps != null) {
+
+ for (Entry<String, Object> entry : rightProps.entrySet()) {
+ String key = entry.getKey();
+ Object leftValue = leftProps.get(key);
+ Object rightValue = entry.getValue();
+
+ if (leftValue == null) {
+ if (rightValue == null) {
+ return false;
+ } else {
+ continue;
+ }
+ }
+
+ if (true == leftValue.equals(rightValue)) {
+ logger.trace("The value of key {} is differnet between properties. {} vs {}", key, leftValue, rightValue);
+ return false;
+ }
+ }
+
+ }
+
+ return true;
+
+ }
+
+ public <T extends GraphNode> Either<List<T>, TitanOperationStatus> getByCriteria(NodeTypeEnum type, Map<String, Object> props, Class<T> clazz) {
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
+ query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName());
+
+ if (props != null && !props.isEmpty()) {
+ for (Map.Entry<String, Object> entry : props.entrySet()) {
+ query = query.has(entry.getKey(), entry.getValue());
+ }
+ }
+ Iterable<TitanVertex> vertices = query.vertices();
+ if (vertices == null) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ List<T> result = new ArrayList<T>();
+
+ while (iterator.hasNext()) {
+ Vertex vertex = iterator.next();
+
+ Map<String, Object> newProp = getProperties(vertex);
+
+ T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz);
+ result.add(element);
+ }
+ if (logger.isDebugEnabled()) {
+ logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size());
+ }
+ if (result.size() == 0) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ return Either.left(result);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ }
+
+ // public <T extends GraphNode> Either<List<T>, TitanOperationStatus>
+ // getByCriteria_tx(NodeTypeEnum type, Map<String, Object> props, Class<T>
+ // clazz) {
+ // Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ // TitanTransaction tx=null;
+ // if (graph.isLeft()) {
+ // try {
+ // TitanGraph tGraph = graph.left().value();
+ // tx = tGraph.newTransaction();
+ //
+ // TitanGraphQuery<? extends TitanGraphQuery> query = tx.query();
+ // query = query.has(GraphPropertiesDictionary.LABEL.getProperty(),
+ // type.getName());
+ //
+ // if (props != null && !props.isEmpty()) {
+ // for (Map.Entry<String, Object> entry : props.entrySet()) {
+ // query = query.has(entry.getKey(), entry.getValue());
+ // }
+ // }
+ // Iterable<TitanVertex> vertices = query.vertices();
+ // if (vertices == null) {
+ // tx.commit();
+ // return Either.right(TitanOperationStatus.NOT_FOUND);
+ // }
+ //
+ //
+ // Iterator<TitanVertex> iterator = vertices.iterator();
+ // List<T> result = new ArrayList<T>();
+ //
+ // while (iterator.hasNext()) {
+ // Vertex vertex = iterator.next();
+ //
+ // Map<String, Object> newProp = getProperties(vertex);
+ //
+ // T element = GraphElementFactory.createElement(type.getName(),
+ // GraphElementTypeEnum.Node, newProp, clazz);
+ // result.add(element);
+ // }
+ // if (logger.isDebugEnabled()) {
+ // logger.debug("Number of fetced nodes in graph for criteria : from type ="
+ // + type + " and properties = " + props + " is " + result.size());
+ // }
+ // tx.commit();
+ // if (result.size() == 0) {
+ // return Either.right(TitanOperationStatus.NOT_FOUND);
+ // }
+ //
+ // return Either.left(result);
+ // } catch (Exception e) {
+ // if (tx != null)
+ // try {
+ // tx.commit();
+ // } catch (Exception e1) {
+ // logger.debug("failed to commit after get", e);
+ // }
+ // if (logger.isDebugEnabled()) {
+ // logger.debug("Failed get by criteria for type = {} and properties = {}. {}", type, props, e);
+ // }
+ // return Either.right(TitanGraphClient.handleTitanException(e));
+ // }
+ //
+ // } else {
+ // if (logger.isDebugEnabled()) {
+ // logger.debug("Failed get by criteria for type = {} and properties {}. error : {}", type, props, graph.right().value());
+ // }
+ // return Either.right(graph.right().value());
+ // }
+ // }
+
+ private boolean vertexLeftContainsRightProps(Map<String, Object> leftProps, Map<String, Object> rightProps) {
+
+ if (rightProps != null) {
+
+ for (Entry<String, Object> entry : rightProps.entrySet()) {
+ String key = entry.getKey();
+ Object leftValue = leftProps.get(key);
+ Object rightValue = entry.getValue();
+ if (leftValue == null) {
+ if (rightValue == null) {
+ continue;
+ } else {
+ logger.debug("The key {} cannot be found in the properties {}", key, leftProps);
+ return false;
+ }
+ }
+
+ if (false == leftValue.equals(rightValue)) {
+ logger.trace("The value of key {} is differnet between properties. {} vs {} ", key, leftValue, rightValue);
+ return false;
+ }
+ }
+
+ }
+
+ return true;
+ }
+
+ public <T extends GraphNode> Either<List<T>, TitanOperationStatus> getByCriteriaWithPradicat(NodeTypeEnum type, Map<String, Entry<TitanPredicate, Object>> props, Class<T> clazz) {
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
+ query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName());
+
+ if (props != null && !props.isEmpty()) {
+ TitanPredicate predicate = null;
+ Object object = null;
+ for (Map.Entry<String, Entry<TitanPredicate, Object>> entry : props.entrySet()) {
+ predicate = entry.getValue().getKey();
+ object = entry.getValue().getValue();
+ query = query.has(entry.getKey(), predicate, object);
+ }
+ }
+ Iterable<TitanVertex> vertices = query.vertices();
+ if (vertices == null) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ List<T> result = new ArrayList<T>();
+
+ while (iterator.hasNext()) {
+ Vertex vertex = iterator.next();
+
+ Map<String, Object> newProp = getProperties(vertex);
+ T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz);
+ result.add(element);
+ }
+ if (result.size() == 0) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ if (logger.isDebugEnabled()) {
+ logger.debug("No nodes in graph for criteria : from type = {} and properties = {}", type, props);
+ }
+ return Either.left(result);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type = {} amd properties = {}. error: {}", type, props, e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type = {} and properties = {}. error : {}", type, props, graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ }
+
+ public <T extends GraphNode> Either<List<T>, TitanOperationStatus> getAll(NodeTypeEnum type, Class<T> clazz) {
+ return getByCriteria(type, null, clazz);
+ }
+
+ /**
+ *
+ * @param node
+ * @param clazz
+ * @return
+ */
+ public <T extends GraphNode> Either<T, TitanOperationStatus> updateNode(GraphNode node, Class<T> clazz) {
+ logger.debug("Try to update node for {}", node.getKeyValueId());
+
+ ImmutablePair<String, Object> keyValueId = node.getKeyValueId();
+ Either<Vertex, TitanOperationStatus> vertexByProperty = getVertexByPropertyAndLabel(keyValueId.getKey(), keyValueId.getValue(), node.getLabel());
+
+ if (vertexByProperty.isLeft()) {
+ try {
+ Vertex vertex = vertexByProperty.left().value();
+
+ Map<String, Object> mapProps = node.toGraphMap();
+
+ for (Map.Entry<String, Object> entry : mapProps.entrySet()) {
+ if (!entry.getKey().equals(node.getUniqueIdKey())) {
+ vertex.property(entry.getKey(), entry.getValue());
+ }
+ }
+
+ Either<Vertex, TitanOperationStatus> vertexByPropertyAndLabel = getVertexByPropertyAndLabel(keyValueId.getKey(), keyValueId.getValue(), node.getLabel());
+ if (vertexByPropertyAndLabel.isRight()) {
+ return Either.right(vertexByPropertyAndLabel.right().value());
+ } else {
+ Map<String, Object> newProp = getProperties(vertexByPropertyAndLabel.left().value());
+ T updateNode = GraphElementFactory.createElement(node.getLabel(), GraphElementTypeEnum.Node, newProp, clazz);
+ return Either.left(updateNode);
+ }
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to update node for {}", node.getKeyValueId(), e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to update node for {} error :{}", node.getKeyValueId(), vertexByProperty.right().value());
+ }
+ return Either.right(vertexByProperty.right().value());
+ }
+
+ }
+
+ public TitanOperationStatus updateVertex(GraphNode node, TitanVertex vertex) {
+ logger.debug("Try to update node for {}", node.getKeyValueId());
+ try {
+
+ Map<String, Object> mapProps = node.toGraphMap();
+
+ for (Map.Entry<String, Object> entry : mapProps.entrySet()) {
+ if (!entry.getKey().equals(node.getUniqueIdKey())) {
+ vertex.property(entry.getKey(), entry.getValue());
+ }
+ }
+
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to update node for {}", node.getKeyValueId(), e);
+ }
+ return TitanGraphClient.handleTitanException(e);
+ }
+ return TitanOperationStatus.OK;
+
+ }
+
+ /**
+ *
+ * @param node
+ * @param clazz
+ * @return
+ */
+ public <T extends GraphNode> Either<T, TitanOperationStatus> deleteNode(GraphNode node, Class<T> clazz) {
+ logger.debug("Try to delete node for {}", node.getKeyValueId());
+ ImmutablePair<String, Object> keyValueId = node.getKeyValueId();
+ return deleteNode(keyValueId.getKey(), keyValueId.getValue(), clazz);
+ }
+
+ /**
+ *
+ * @param keyName
+ * @param keyValue
+ * @param clazz
+ * @return
+ */
+ public <T extends GraphNode> Either<T, TitanOperationStatus> deleteNode(String keyName, Object keyValue, Class<T> clazz) {
+ Either<TitanVertex, TitanOperationStatus> vertexByProperty = getVertexByProperty(keyName, keyValue);
+
+ if (vertexByProperty.isLeft()) {
+ try {
+ Vertex vertex = vertexByProperty.left().value();
+
+ Map<String, Object> properties = getProperties(vertex);
+ if (properties != null) {
+ String label = (String) properties.get(GraphPropertiesDictionary.LABEL.getProperty());
+
+ T node = GraphElementFactory.createElement(label, GraphElementTypeEnum.Node, properties, clazz);
+ if (node != null) {
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ TitanGraph tGraph = graph.left().value();
+ vertex.remove();
+ } else {
+ return Either.right(graph.right().value());
+ }
+ return Either.left(node);
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to delete node for {} = {}. Missing label property on node", keyName, keyValue);
+ }
+ return Either.right(TitanOperationStatus.MISSING_NODE_LABEL);
+ }
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to delete node for {} = {}. Missing label property on node", keyName, keyValue);
+ }
+ return Either.right(TitanOperationStatus.MISSING_NODE_LABEL);
+ }
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to delete node for {} = {}. error: {}", keyName, keyValue, e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ return Either.right(vertexByProperty.right().value());
+ }
+ }
+
+ public Either<GraphRelation, TitanOperationStatus> deleteRelation(GraphRelation relation) {
+ logger.debug("try to delete relation from [{}] to [{}]", relation.getFrom(), relation.getTo());
+ RelationEndPoint from = relation.getFrom();
+ RelationEndPoint to = relation.getTo();
+ ImmutablePair<String, Object> fromKeyId = new ImmutablePair<String, Object>(from.getIdName(), from.getIdValue());
+ ImmutablePair<String, Object> toKeyId = new ImmutablePair<String, Object>(to.getIdName(), to.getIdValue());
+
+ return deleteEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName());
+
+ }
+
+ public Either<GraphRelation, TitanOperationStatus> deleteRelation(GraphNode from, GraphNode to, GraphEdgeLabels label) {
+ logger.debug("try to delete relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId());
+ return deleteEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel());
+ }
+
+ private Either<GraphRelation, TitanOperationStatus> deleteEdge(String type, ImmutablePair<String, Object> fromKeyId, ImmutablePair<String, Object> toKeyId, String fromLabel, String toLabel) {
+ Either<Edge, TitanOperationStatus> edgeS = getEdgeByVerticies(fromKeyId.getKey(), fromKeyId.getValue(), toKeyId.getKey(), toKeyId.getValue(), type);
+ if (edgeS.isLeft()) {
+ try {
+ Edge edge = edgeS.left().value();
+
+ Vertex vertexOut = edge.outVertex();
+ Vertex vertexIn = edge.inVertex();
+
+ GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class);
+ GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class);
+
+ GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn);
+
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+
+ if (graph.isLeft()) {
+ edge.remove();
+ ;
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to delete relation {} from {} to {}. error: {}", type, fromKeyId, toKeyId, graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ return Either.left(newRelation);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to delete relation {} from {} to {}. error: {}", type, fromKeyId, toKeyId, e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to delete relation {} from {} to {}. error: {}", type, fromKeyId, toKeyId, edgeS.right().value());
+ }
+ return Either.right(edgeS.right().value());
+ }
+ }
+
+ public void setTitanGraphClient(TitanGraphClient titanGraphClient) {
+ this.titanClient = titanGraphClient;
+ }
+
+ public Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation(GraphRelation relation) {
+
+ RelationEndPoint to = relation.getTo();
+ ImmutablePair<String, Object> toKeyId = new ImmutablePair<String, Object>(to.getIdName(), to.getIdValue());
+
+ return deleteIncomingEdge(relation.getType(), toKeyId);
+
+ }
+
+ private Either<GraphRelation, TitanOperationStatus> deleteIncomingEdge(String type, ImmutablePair<String, Object> toKeyId) {
+
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+
+ if (graph.isLeft()) {
+ Either<TitanVertex, TitanOperationStatus> rootVertexResult = getVertexByProperty(toKeyId.getKey(), toKeyId.getValue());
+ if (rootVertexResult.isLeft()) {
+ Vertex rootVertex = rootVertexResult.left().value();
+ Iterator<Edge> edgesIterator = rootVertex.edges(Direction.IN, type);
+ if (edgesIterator != null) {
+
+ Edge edge = null;
+
+ if (edgesIterator.hasNext()) {
+ edge = edgesIterator.next();
+ if (edgesIterator.hasNext()) {
+ return Either.right(TitanOperationStatus.MULTIPLE_EDGES_WITH_SAME_LABEL);
+ }
+ } else {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ logger.debug("Find the tail vertex of the edge of type {} to vertex {}", type, toKeyId);
+ Vertex vertexOut = edge.outVertex();
+ String fromLabel = vertexOut.value(GraphPropertiesDictionary.LABEL.getProperty());
+ String toLabel = rootVertex.value(GraphPropertiesDictionary.LABEL.getProperty());
+ logger.debug("The label of the outgoing vertex is {}", fromLabel);
+ GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class);
+
+ GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(rootVertex), GraphNode.class);
+
+ GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn);
+
+ edge.remove();
+
+ return Either.left(newRelation);
+
+ } else {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ } else {
+ return Either.right(graph.right().value());
+ }
+
+ } else {
+ return Either.right(graph.right().value());
+ }
+
+ }
+
+ public Either<GraphRelation, TitanOperationStatus> deleteOutgoingRelation(GraphRelation relation) {
+
+ RelationEndPoint from = relation.getFrom();
+ ImmutablePair<String, Object> fromKeyId = new ImmutablePair<String, Object>(from.getIdName(), from.getIdValue());
+
+ return deleteOutgoingEdge(relation.getType(), fromKeyId);
+
+ }
+
+ private Either<GraphRelation, TitanOperationStatus> deleteOutgoingEdge(String type, ImmutablePair<String, Object> toKeyId) {
+
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+
+ if (graph.isLeft()) {
+ Either<TitanVertex, TitanOperationStatus> rootVertexResult = getVertexByProperty(toKeyId.getKey(), toKeyId.getValue());
+ if (rootVertexResult.isLeft()) {
+ Vertex rootVertex = rootVertexResult.left().value();
+ Iterator<Edge> edgesIterator = rootVertex.edges(Direction.OUT, type);
+ if (edgesIterator != null) {
+
+ Edge edge = null;
+
+ if (edgesIterator.hasNext()) {
+ edge = edgesIterator.next();
+ if (edgesIterator.hasNext()) {
+ return Either.right(TitanOperationStatus.MULTIPLE_EDGES_WITH_SAME_LABEL);
+ }
+ } else {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ logger.debug("Find the tail vertex of the edge of type {} to vertex ", type, toKeyId);
+ Vertex vertexIn = edge.inVertex();
+ String toLabel = vertexIn.value(GraphPropertiesDictionary.LABEL.getProperty());
+ String fromLabel = rootVertex.value(GraphPropertiesDictionary.LABEL.getProperty());
+ logger.debug("The label of the tail vertex is {}", toLabel);
+ GraphNode nodeFrom = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(rootVertex), GraphNode.class);
+
+ GraphNode nodeTo = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class);
+
+ GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeFrom, nodeTo);
+
+ edge.remove();
+
+ return Either.left(newRelation);
+
+ } else {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ } else {
+ return Either.right(graph.right().value());
+ }
+
+ } else {
+ return Either.right(graph.right().value());
+ }
+ }
+
+ /**
+ *
+ * @param id
+ * @return
+ */
+
+ public TitanOperationStatus lockElement(String id, NodeTypeEnum type) {
+
+ StringBuffer lockId = new StringBuffer(LOCK_NODE_PREFIX);
+ lockId.append(type.getName()).append("_").append(id);
+ return lockNode(lockId.toString());
+ }
+
+ public TitanOperationStatus lockElement(GraphNode node) {
+
+ StringBuffer lockId = createLockElementId(node);
+
+ return lockNode(lockId.toString());
+ }
+
+ private TitanOperationStatus lockNode(String lockId) {
+ TitanOperationStatus status = TitanOperationStatus.OK;
+
+ GraphNodeLock lockNode = new GraphNodeLock(lockId);
+
+ Either<GraphNodeLock, TitanOperationStatus> lockNodeNew = createNode(lockNode, GraphNodeLock.class);
+ if (lockNodeNew.isLeft()) {
+ logger.debug("before commit, Lock node created for {}", lockId);
+ return titanClient.commit();
+ } else {
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ TitanGraph tGraph = graph.left().value();
+ Either<TitanVertex, TitanOperationStatus> vertex = getVertexByProperty(lockNode.getUniqueIdKey(), lockNode.getUniqueId());
+ if (vertex.isLeft()) {
+ status = relockNode(lockNode, lockNodeNew, tGraph, vertex);
+ } else {
+ status = vertex.right().value();
+ }
+ } else {
+ status = graph.right().value();
+ }
+ }
+ return status;
+ }
+
+ private TitanOperationStatus relockNode(GraphNodeLock lockNode, Either<GraphNodeLock, TitanOperationStatus> lockNodeNew, TitanGraph tGraph, Either<TitanVertex, TitanOperationStatus> vertex) {
+ TitanOperationStatus status = TitanOperationStatus.OK;
+ Long time = vertex.left().value().value(GraphPropertiesDictionary.CREATION_DATE.getProperty());
+ Long lockTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanLockTimeout();
+ if (time + lockTimeout * 1000 < System.currentTimeMillis()) {
+ logger.debug("Found not released lock node with id {}", lockNode.getUniqueId());
+ vertex.left().value().remove();
+ lockNodeNew = createNode(lockNode, GraphNodeLock.class);
+ if (lockNodeNew.isLeft()) {
+ logger.debug("Lock node created for {}", lockNode.getUniqueIdKey());
+ return titanClient.commit();
+ } else {
+ logger.debug("Failed Lock node for {} . Commit transacton for deleted previous vertex .", lockNode.getUniqueIdKey());
+ titanClient.commit();
+ status = checkLockError(lockNode.getUniqueIdKey(), lockNodeNew);
+ }
+ } else {
+ logger.debug("Failed Lock node for {} rollback transacton", lockNode.getUniqueIdKey());
+ titanClient.rollback();
+ status = checkLockError(lockNode.getUniqueIdKey(), lockNodeNew);
+ }
+ return status;
+ }
+
+ public <T extends GraphNode> Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> getChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class<T> clazz, boolean withEdges) {
+
+ List<ImmutablePair<T, GraphEdge>> immutablePairs = new ArrayList<ImmutablePair<T, GraphEdge>>();
+
+ Either<TitanGraph, TitanOperationStatus> graphRes = titanClient.getGraph();
+ if (graphRes.isRight()) {
+ logger.error("Failed to retrieve graph. status is {}", graphRes);
+ return Either.right(graphRes.right().value());
+ }
+
+ TitanGraph titanGraph = graphRes.left().value();
+ @SuppressWarnings("unchecked")
+ Iterable<TitanVertex> vertices = titanGraph.query().has(key, uniqueId).vertices();
+ if (vertices == null || false == vertices.iterator().hasNext()) {
+ return Either.right(TitanOperationStatus.INVALID_ID);
+ }
+
+ Vertex rootVertex = vertices.iterator().next();
+
+ Iterator<Edge> edgesCreatorIterator = rootVertex.edges(Direction.OUT, edgeType.getProperty());
+ if (edgesCreatorIterator != null) {
+ while (edgesCreatorIterator.hasNext()) {
+ Edge edge = edgesCreatorIterator.next();
+ GraphEdge graphEdge = null;
+
+ if (withEdges) {
+ Map<String, Object> edgeProps = getProperties(edge);
+ GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label());
+ graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps);
+ }
+
+ Vertex outgoingVertex = edge.inVertex();
+ Map<String, Object> properties = getProperties(outgoingVertex);
+ T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz);
+
+ ImmutablePair<T, GraphEdge> immutablePair = new ImmutablePair<T, GraphEdge>(clazz.cast(data), graphEdge);
+ immutablePairs.add(immutablePair);
+ }
+ }
+
+ if (true == immutablePairs.isEmpty()) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ return Either.left(immutablePairs);
+
+ }
+
+ public Either<List<ImmutablePair<TitanVertex, Edge>>, TitanOperationStatus> getChildrenVertecies(String key, String uniqueId, GraphEdgeLabels edgeType) {
+
+ List<ImmutablePair<TitanVertex, Edge>> immutablePairs = new ArrayList<ImmutablePair<TitanVertex, Edge>>();
+
+ Either<TitanGraph, TitanOperationStatus> graphRes = titanClient.getGraph();
+ if (graphRes.isRight()) {
+ logger.error("Failed to retrieve graph. status is {}", graphRes);
+ return Either.right(graphRes.right().value());
+ }
+
+ TitanGraph titanGraph = graphRes.left().value();
+ @SuppressWarnings("unchecked")
+ Iterable<TitanVertex> vertices = titanGraph.query().has(key, uniqueId).vertices();
+ if (vertices == null || false == vertices.iterator().hasNext()) {
+ return Either.right(TitanOperationStatus.INVALID_ID);
+ }
+
+ Vertex rootVertex = vertices.iterator().next();
+
+ Iterator<Edge> edgesCreatorIterator = rootVertex.edges(Direction.OUT, edgeType.getProperty());
+ if (edgesCreatorIterator != null) {
+ while (edgesCreatorIterator.hasNext()) {
+ Edge edge = edgesCreatorIterator.next();
+ TitanVertex vertex = (TitanVertex) edge.inVertex();
+
+ ImmutablePair<TitanVertex, Edge> immutablePair = new ImmutablePair<TitanVertex, Edge>(vertex, edge);
+ immutablePairs.add(immutablePair);
+ }
+ }
+ if (true == immutablePairs.isEmpty()) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ return Either.left(immutablePairs);
+
+ }
+
+ public <T extends GraphNode> Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> getChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class<T> clazz) {
+ return this.getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz, true);
+ }
+
+ private TitanOperationStatus checkLockError(String lockId, Either<GraphNodeLock, TitanOperationStatus> lockNodeNew) {
+ TitanOperationStatus status;
+ TitanOperationStatus error = lockNodeNew.right().value();
+ logger.debug("Failed to Lock node for {} error = {}", lockId, error);
+ if (error.equals(TitanOperationStatus.TITAN_SCHEMA_VIOLATION) || error.equals(TitanOperationStatus.ILLEGAL_ARGUMENT)) {
+ status = TitanOperationStatus.ALREADY_LOCKED;
+ } else {
+ status = error;
+ }
+ return status;
+ }
+
+ /**
+ *
+ * @param node
+ * @return
+ */
+ public TitanOperationStatus releaseElement(GraphNode node) {
+ StringBuffer lockId = createLockElementId(node);
+
+ return unlockNode(lockId);
+ }
+
+ private TitanOperationStatus unlockNode(StringBuffer lockId) {
+ GraphNodeLock lockNode = new GraphNodeLock(lockId.toString());
+
+ Either<GraphNodeLock, TitanOperationStatus> lockNodeNew = deleteNode(lockNode, GraphNodeLock.class);
+ if (lockNodeNew.isLeft()) {
+ logger.debug("Lock node released for lock id = {}", lockId);
+ return titanClient.commit();
+ } else {
+ titanClient.rollback();
+ TitanOperationStatus error = lockNodeNew.right().value();
+ logger.debug("Failed to Release node for lock id {} error = {}", lockId, error);
+ return error;
+ }
+ }
+
+ public TitanOperationStatus releaseElement(String id, NodeTypeEnum type) {
+ StringBuffer lockId = new StringBuffer(LOCK_NODE_PREFIX);
+ lockId.append(type.getName()).append("_").append(id);
+ return unlockNode(lockId);
+ }
+
+ private StringBuffer createLockElementId(GraphNode node) {
+ StringBuffer lockId = new StringBuffer(LOCK_NODE_PREFIX);
+ lockId.append(node.getLabel()).append("_").append(node.getUniqueId());
+ return lockId;
+ }
+
+ public <T extends GraphNode> Either<ImmutablePair<T, GraphEdge>, TitanOperationStatus> getChild(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class<T> clazz) {
+
+ Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> childrenNodes = getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz);
+
+ if (childrenNodes.isRight()) {
+ return Either.right(childrenNodes.right().value());
+ }
+
+ List<ImmutablePair<T, GraphEdge>> value = childrenNodes.left().value();
+
+ if (value.size() > 1) {
+ return Either.right(TitanOperationStatus.MULTIPLE_CHILDS_WITH_SAME_EDGE);
+ }
+
+ return Either.left(value.get(0));
+
+ }
+
+ public ImmutablePair<TitanVertex, Edge> getChildVertex(TitanVertex vertex, GraphEdgeLabels edgeType) {
+
+ ImmutablePair<TitanVertex, Edge> pair = null;
+ Iterator<Edge> edges = vertex.edges(Direction.OUT, edgeType.getProperty());
+ if (edges.hasNext()) {
+ // get only first edge
+ Edge edge = edges.next();
+ pair = new ImmutablePair<TitanVertex, Edge>((TitanVertex) edge.inVertex(), edge);
+ }
+ return pair;
+ }
+
+ public <T extends GraphNode> Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> getParentNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class<T> clazz) {
+
+ List<ImmutablePair<T, GraphEdge>> immutablePairs = new ArrayList<ImmutablePair<T, GraphEdge>>();
+
+ T data = null;
+ GraphEdge graphEdge = null;
+
+ Either<TitanGraph, TitanOperationStatus> graphRes = titanClient.getGraph();
+ if (graphRes.isRight()) {
+ logger.error("Failed to retrieve graph. status is {}", graphRes);
+ return Either.right(graphRes.right().value());
+ }
+
+ TitanGraph titanGraph = graphRes.left().value();
+ @SuppressWarnings("unchecked")
+ Iterable<TitanVertex> vertices = titanGraph.query().has(key, uniqueId).vertices();
+ if (vertices == null || false == vertices.iterator().hasNext()) {
+ return Either.right(TitanOperationStatus.INVALID_ID);
+ }
+
+ Vertex rootVertex = vertices.iterator().next();
+
+ Iterator<Edge> edgesCreatorIterator = rootVertex.edges(Direction.IN, edgeType.name());
+ if (edgesCreatorIterator != null) {
+ while (edgesCreatorIterator.hasNext()) {
+ Edge edge = edgesCreatorIterator.next();
+ Map<String, Object> edgeProps = getProperties(edge);
+ GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label());
+ graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps);
+
+ Vertex outgoingVertex = edge.outVertex();
+ Map<String, Object> properties = getProperties(outgoingVertex);
+ data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz);
+
+ ImmutablePair<T, GraphEdge> immutablePair = new ImmutablePair<T, GraphEdge>(clazz.cast(data), graphEdge);
+ immutablePairs.add(immutablePair);
+ }
+ }
+
+ if (true == immutablePairs.isEmpty()) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ return Either.left(immutablePairs);
+
+ }
+
+ public <T extends GraphNode> Either<ImmutablePair<T, GraphEdge>, TitanOperationStatus> getParentNode(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class<T> clazz) {
+
+ Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> parentNodesRes = this.getParentNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz);
+
+ if (parentNodesRes.isRight()) {
+ logger.debug("failed to get edge key:{} uniqueId:{} edgeType {} nodeTypeEnum: {}, reason:{}", key, uniqueId, edgeType, nodeTypeEnum, parentNodesRes.right().value());
+ return Either.right(parentNodesRes.right().value());
+ }
+
+ List<ImmutablePair<T, GraphEdge>> value = parentNodesRes.left().value();
+
+ if (value.size() > 1) {
+ return Either.right(TitanOperationStatus.MULTIPLE_CHILDS_WITH_SAME_EDGE);
+ }
+
+ return Either.left(value.get(0));
+ }
+
+ public <T extends GraphNode> Either<ImmutablePair<T, GraphEdge>, TitanOperationStatus> getChildByEdgeCriteria(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class<T> clazz, Map<String, Object> edgeProperties) {
+
+ Either<Edge, TitanOperationStatus> outgoingEdgeByCriteria = getOutgoingEdgeByCriteria(key, uniqueId, edgeType, edgeProperties);
+ if (outgoingEdgeByCriteria.isRight()) {
+ TitanOperationStatus status = outgoingEdgeByCriteria.right().value();
+ logger.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", uniqueId, edgeType, edgeProperties);
+ return Either.right(status);
+ }
+
+ Edge edge = outgoingEdgeByCriteria.left().value();
+ Map<String, Object> edgeProps = getProperties(edge);
+ GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label());
+ GraphEdge graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps);
+
+ Vertex outgoingVertex = edge.inVertex();
+ Map<String, Object> properties = getProperties(outgoingVertex);
+ T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz);
+
+ ImmutablePair<T, GraphEdge> immutablePair = new ImmutablePair<T, GraphEdge>(clazz.cast(data), graphEdge);
+
+ return Either.left(immutablePair);
+ }
+
+ public Either<ImmutablePair<TitanVertex, Edge>, TitanOperationStatus> getChildByEdgeCriteria(TitanVertex vertex, GraphEdgeLabels edgeType, Map<String, Object> edgeProperties) {
+
+ Either<Edge, TitanOperationStatus> outgoingEdgeByCriteria = getOutgoingEdgeByCriteria(vertex, edgeType, edgeProperties);
+ if (outgoingEdgeByCriteria.isRight()) {
+ TitanOperationStatus status = outgoingEdgeByCriteria.right().value();
+ logger.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", vertex, edgeType, edgeProperties);
+ return Either.right(status);
+ }
+ Edge edge = outgoingEdgeByCriteria.left().value();
+
+ TitanVertex outgoingVertex = (TitanVertex) edge.inVertex();
+
+ ImmutablePair<TitanVertex, Edge> immutablePair = new ImmutablePair<TitanVertex, Edge>(outgoingVertex, edge);
+
+ return Either.left(immutablePair);
+ }
+
+ public Either<Edge, TitanOperationStatus> getOutgoingEdgeByCriteria(String key, String value, GraphEdgeLabels label, Map<String, Object> props) {
+
+ Either<TitanVertex, TitanOperationStatus> vertexFrom = getVertexByProperty(key, value);
+ if (vertexFrom.isRight()) {
+ TitanOperationStatus status = vertexFrom.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ return Either.right(TitanOperationStatus.INVALID_ID);
+ }
+ return Either.right(status);
+ }
+
+ return getOutgoingEdgeByCriteria(vertexFrom.left().value(), label, props);
+ }
+
+ public Either<Edge, TitanOperationStatus> getOutgoingEdgeByCriteria(TitanVertex vertex, GraphEdgeLabels label, Map<String, Object> props) {
+
+ TitanVertexQuery<?> query = vertex.query();
+ query = query.direction(Direction.OUT).labels(label.getProperty());
+
+ if (props != null && !props.isEmpty()) {
+ for (Map.Entry<String, Object> entry : props.entrySet()) {
+ query = query.has(entry.getKey(), entry.getValue());
+ }
+ }
+ Edge matchingEdge = null;
+ Iterable<TitanEdge> edges = query.edges();
+ if (edges == null) {
+ logger.debug("No edges in graph for criteria");
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ Iterator<TitanEdge> eIter = edges.iterator();
+ if (eIter.hasNext()) {
+ Edge edge = eIter.next();
+ matchingEdge = edge;
+ }
+
+ if (matchingEdge == null) {
+ logger.debug("No edges in graph for criteria");
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ return Either.left(matchingEdge);
+ }
+
+ public <T extends GraphNode> Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> deleteChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class<T> clazz) {
+
+ List<ImmutablePair<T, GraphEdge>> result = new ArrayList<ImmutablePair<T, GraphEdge>>();
+
+ Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> childrenNodesRes = getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz);
+
+ if (childrenNodesRes.isRight()) {
+ TitanOperationStatus status = childrenNodesRes.right().value();
+ return Either.right(status);
+ }
+
+ List<ImmutablePair<T, GraphEdge>> list = childrenNodesRes.left().value();
+ for (ImmutablePair<T, GraphEdge> pair : list) {
+ T node = pair.getKey();
+ Either<T, TitanOperationStatus> deleteNodeRes = this.deleteNode(node, clazz);
+ if (deleteNodeRes.isRight()) {
+ TitanOperationStatus status = deleteNodeRes.right().value();
+ logger.error("Failed to delete node {} . status is {}", node, status);
+ return Either.right(status);
+ }
+ ImmutablePair<T, GraphEdge> deletedPair = new ImmutablePair<T, GraphEdge>(node, pair.getValue());
+ result.add(deletedPair);
+ }
+
+ return Either.left(result);
+
+ }
+
+ public void setProperties(Element element, Map<String, Object> properties) {
+
+ if (properties != null && false == properties.isEmpty()) {
+
+ Object[] propertyKeyValues = new Object[properties.size() * 2];
+ int i = 0;
+ for (Entry<String, Object> entry : properties.entrySet()) {
+ propertyKeyValues[i++] = entry.getKey();
+ propertyKeyValues[i++] = entry.getValue();
+ }
+
+ ElementHelper.attachProperties(element, propertyKeyValues);
+
+ }
+
+ }
+
+ public Map<String, Object> getProperties(Element element) {
+
+ Map<String, Object> result = new HashMap<String, Object>();
+
+ if (element != null && element.keys() != null && element.keys().size() > 0) {
+ Map<String, Property> propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()]));
+
+ for (Entry<String, Property> entry : propertyMap.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue().value();
+
+ result.put(key, value);
+ }
+ }
+ return result;
+ }
+
+ public Object getProperty(TitanVertex vertex, String key) {
+ PropertyKey propertyKey = titanClient.getGraph().left().value().getPropertyKey(key);
+ Object value = vertex.valueOrNull(propertyKey);
+ return value;
+ }
+
+ public Object getProperty(Edge edge, String key) {
+ Object value = null;
+ Property<Object> property = edge.property(key);
+ if (property != null) {
+ return property.orElse(null);
+ }
+ return value;
+ }
+
+ public <T extends GraphNode> Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> getChildrenByEdgeCriteria(Vertex vertex, String vertexUniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class<T> clazz,
+ Map<String, Object> edgeProperties) {
+
+ List<ImmutablePair<T, GraphEdge>> result = new ArrayList<>();
+
+ Either<List<Edge>, TitanOperationStatus> outgoingEdgeByCriteria = getOutgoingEdgesByCriteria(vertex, edgeType, edgeProperties);
+ if (outgoingEdgeByCriteria.isRight()) {
+ TitanOperationStatus status = outgoingEdgeByCriteria.right().value();
+ logger.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", vertexUniqueId, edgeType, edgeProperties);
+ return Either.right(status);
+ }
+
+ List<Edge> edges = outgoingEdgeByCriteria.left().value();
+ if (edges != null) {
+ for (Edge edge : edges) {
+ Map<String, Object> edgeProps = getProperties(edge);
+ GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label());
+ GraphEdge graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps);
+
+ Vertex outgoingVertex = edge.inVertex();
+ Map<String, Object> properties = getProperties(outgoingVertex);
+ T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz);
+
+ ImmutablePair<T, GraphEdge> immutablePair = new ImmutablePair<T, GraphEdge>(clazz.cast(data), graphEdge);
+ result.add(immutablePair);
+ }
+ }
+
+ return Either.left(result);
+ }
+
+ public Either<List<Edge>, TitanOperationStatus> getOutgoingEdgesByCriteria(Vertex vertexFrom, GraphEdgeLabels label, Map<String, Object> props) {
+
+ List<Edge> edgesResult = new ArrayList<>();
+
+ TitanVertex titanVertex = (TitanVertex) vertexFrom;
+ TitanVertexQuery<?> query = titanVertex.query();
+
+ query = query.direction(Direction.OUT).labels(label.getProperty());
+
+ if (props != null && !props.isEmpty()) {
+ for (Map.Entry<String, Object> entry : props.entrySet()) {
+ query = query.has(entry.getKey(), entry.getValue());
+ }
+ }
+
+ Iterable<TitanEdge> edges = query.edges();
+ Iterator<TitanEdge> eIter = edges.iterator();
+ if (edges == null || false == eIter.hasNext()) {
+ logger.debug("No edges found in graph for criteria (label = {} properties={})", label.getProperty(), props);
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ while (eIter.hasNext()) {
+ Edge edge = eIter.next();
+ edgesResult.add(edge);
+ }
+
+ if (edgesResult.isEmpty()) {
+ logger.debug("No edges found in graph for criteria (label = {} properties={})", label.getProperty(), props);
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ return Either.left(edgesResult);
+
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java
new file mode 100644
index 0000000000..68a05a91bf
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java
@@ -0,0 +1,872 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.titan;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+
+import javax.annotation.PostConstruct;
+
+import org.apache.commons.configuration.BaseConfiguration;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.T;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.resources.data.CategoryData;
+import org.openecomp.sdc.be.resources.data.ResourceCategoryData;
+import org.openecomp.sdc.be.resources.data.ServiceCategoryData;
+import org.openecomp.sdc.be.resources.data.UserData;
+import org.openecomp.sdc.common.config.EcompErrorName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import com.thinkaurelius.titan.core.InvalidElementException;
+import com.thinkaurelius.titan.core.InvalidIDException;
+import com.thinkaurelius.titan.core.PropertyKey;
+import com.thinkaurelius.titan.core.QueryException;
+import com.thinkaurelius.titan.core.SchemaViolationException;
+import com.thinkaurelius.titan.core.TitanConfigurationException;
+import com.thinkaurelius.titan.core.TitanFactory;
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanGraphQuery;
+import com.thinkaurelius.titan.core.TitanVertex;
+import com.thinkaurelius.titan.core.TitanVertexProperty;
+import com.thinkaurelius.titan.core.schema.ConsistencyModifier;
+import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
+import com.thinkaurelius.titan.core.schema.TitanManagement;
+import com.thinkaurelius.titan.core.util.TitanCleanup;
+import com.thinkaurelius.titan.diskstorage.ResourceUnavailableException;
+import com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException;
+import com.thinkaurelius.titan.graphdb.database.idassigner.IDPoolExhaustedException;
+
+
+import fj.data.Either;
+
+@Component("titan-client")
+public class TitanGraphClient {
+
+ private static Logger logger = LoggerFactory.getLogger(TitanGraphClient.class.getName());
+ private static Logger healthLogger = LoggerFactory.getLogger("titan.healthcheck");
+
+ private static final String HEALTH_CHECK = GraphPropertiesDictionary.HEALTH_CHECK.getProperty();
+ private static final String OK = "GOOD";
+
+ private class HealthCheckTask implements Callable<Vertex> {
+ @Override
+ public Vertex call() {
+
+ TitanVertex v = (TitanVertex) graph.query().has(HEALTH_CHECK, OK).vertices().iterator().next();
+ TitanVertexProperty<String> property = v.property("healthcheck", OK + "_" + System.currentTimeMillis());
+ healthLogger.trace("Health Check Node Found...{}", v.property(HEALTH_CHECK));
+ graph.tx().commit();
+
+ // Vertex v = graph.getVertices(HEALTH_CHECK, OK).iterator().next();
+ // v.setProperty("healthcheck", OK + "_" +
+ // System.currentTimeMillis());
+ // graph.commit();
+ // healthLogger.trace("Health Check Node
+ // Found..."+v.getProperty(HEALTH_CHECK) );
+ return v;
+ }
+ }
+
+ private class HealthCheckScheduledTask implements Runnable {
+ @Override
+ public void run() {
+ healthLogger.trace("Executing TITAN Health Check Task - Start");
+ boolean healthStatus = isGraphOpen();
+ healthLogger.trace("Executing TITAN Health Check Task - Status = {}", healthStatus);
+ if (healthStatus != lastHealthState) {
+ logger.trace("TITAN Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
+ lastHealthState = healthStatus;
+ logAlarm();
+ }
+ }
+ }
+
+ private class ReconnectTask implements Runnable {
+ @Override
+ public void run() {
+ logger.trace("Trying to reconnect to Titan...");
+ if (graph == null) {
+ createGraph(titanCfgFile, true);
+ }
+ }
+ }
+
+ private TitanGraph graph;
+
+ // Health Check Variables
+
+ /**
+ * This executor will execute the health check task on a callable task that
+ * can be executed with a timeout.
+ */
+ ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable r) {
+ return new Thread(r, "Titan-Health-Check-Thread");
+ }
+ });
+ private long healthCheckReadTimeout = 2;
+ HealthCheckTask healthCallableTask = new HealthCheckTask();
+ HealthCheckScheduledTask healthCheckScheduledTask = new HealthCheckScheduledTask();
+ boolean lastHealthState = false;
+
+ // Reconnection variables
+ private ScheduledExecutorService reconnectScheduler = null;
+ private ScheduledExecutorService healthCheckScheduler = null;
+ private Runnable reconnectTask = null;
+ private long reconnectInterval = 3;
+ @SuppressWarnings("rawtypes")
+ private Future reconnectFuture;
+
+ private String titanCfgFile = null;
+
+ public TitanGraphClient() {
+ super();
+
+ // Initialize a single threaded scheduler for health-check
+ this.healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable r) {
+ return new Thread(r, "Titan-Health-Check-Task");
+ }
+ });
+
+ healthCheckReadTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getTitanHealthCheckReadTimeout(2);
+ reconnectInterval = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getTitanReconnectIntervalInSeconds(3);
+
+ logger.info("** TitanGraphClient created");
+ }
+
+ @PostConstruct
+ public TitanOperationStatus createGraph() {
+
+ logger.info("** createGraph started **");
+
+ if (ConfigurationManager.getConfigurationManager().getConfiguration().getTitanInMemoryGraph()) {
+ BaseConfiguration conf = new BaseConfiguration();
+ conf.setProperty("storage.backend", "inmemory");
+ graph = TitanFactory.open(conf);
+
+ createIndexesAndDefaults();
+
+ logger.info("** in memory graph created");
+ return TitanOperationStatus.OK;
+ } else {
+ this.titanCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile();
+ if (titanCfgFile == null || titanCfgFile.isEmpty()) {
+ titanCfgFile = "config/titan.properties";
+ }
+
+ // yavivi
+ // In case connection failed on init time, schedule a reconnect task
+ // in the BG
+ TitanOperationStatus status = createGraph(titanCfgFile);
+ logger.debug("Create Titan graph status {}", status);
+ if (status != TitanOperationStatus.OK) {
+ this.startReconnectTask();
+ }
+
+ return status;
+ }
+ }
+
+ private void startHealthCheckTask() {
+ this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS);
+ }
+
+ /**
+ * This method will be invoked ONLY on init time in case Titan storage is
+ * down.
+ */
+ private void startReconnectTask() {
+ this.reconnectTask = new ReconnectTask();
+ // Initialize a single threaded scheduler
+ this.reconnectScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable r) {
+ return new Thread(r, "Titan-Reconnect-Task");
+ }
+ });
+
+ logger.info("Scheduling reconnect task {} with interval of {} seconds", reconnectTask, reconnectInterval);
+ reconnectFuture = this.reconnectScheduler.scheduleAtFixedRate(this.reconnectTask, 0, this.reconnectInterval,
+ TimeUnit.SECONDS);
+ }
+
+ public void cleanupGraph() {
+ if (graph != null) {
+ // graph.shutdown();
+ graph.close();
+ TitanCleanup.clear(graph);
+ }
+ }
+
+ public TitanOperationStatus createGraph(String titanCfgFile) {
+ logger.info("** createGraph with " + titanCfgFile + " started");
+ return createGraph(titanCfgFile, true);
+ }
+
+ public TitanOperationStatus createGraph(String titanCfgFile, boolean initializeGraph) {
+ logger.info("** createGraph with " + titanCfgFile + " and initializeGraph=" + initializeGraph + " started");
+ try {
+ logger.info("createGraph : try to load file " + titanCfgFile);
+ graph = TitanFactory.open(titanCfgFile);
+ if (graph == null) {
+ return TitanOperationStatus.NOT_CREATED;
+ }
+
+ } catch (Exception e) {
+ this.graph = null;
+ logger.info("createGraph : failed to open Titan graph with configuration file: " + titanCfgFile);
+ logger.trace("createGraph : failed to open Titan graph. ", e);
+ return TitanOperationStatus.NOT_CONNECTED;
+ }
+ if (true == initializeGraph) {
+ createIndexesAndDefaults();
+ }
+ logger.info("** Titan graph created ");
+
+ // Do some post creation actions
+ this.onGraphOpened();
+
+ return TitanOperationStatus.OK;
+ }
+
+ private void onGraphOpened() {
+ // if a reconnect task is running, cancel it.
+ if (this.reconnectFuture != null) {
+ logger.info("** Cancelling Titan reconnect task");
+ reconnectFuture.cancel(true);
+ }
+
+ // create health-check node
+ if (!graph.query().has(HEALTH_CHECK, OK).vertices().iterator().hasNext()) {
+ logger.trace("Healthcheck Singleton node does not exist, Creating healthcheck node...");
+ Vertex healthCheckNode = graph.addVertex();
+ healthCheckNode.property(HEALTH_CHECK, OK);
+ logger.trace("Healthcheck node created successfully. ID={}", healthCheckNode.property(T.id.getAccessor()));
+ graph.tx().commit();
+ } else {
+ logger.trace("Skipping Healthcheck Singleton node creation. Already exist...");
+ }
+ this.startHealthCheckTask();
+ }
+
+ private void createIndexesAndDefaults() {
+ createVertexIndixes();
+ createEdgeIndixes();
+ createDefaultUsers();
+ // createCategories();
+ }
+
+ public Either<TitanGraph, TitanOperationStatus> getGraph() {
+ if (graph != null) {
+ return Either.left(graph);
+ } else {
+ return Either.right(TitanOperationStatus.NOT_CREATED);
+ }
+ }
+
+ private TitanOperationStatus createVertexIndixes() {
+ logger.info("** createVertexIndixes started");
+ if (graph != null) {
+ // TitanManagement graphMgt = graph.getManagementSystem();
+ TitanManagement graphMgt = graph.openManagement();
+ TitanGraphIndex index = null;
+ for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) {
+ PropertyKey propKey = null;
+ if (!graphMgt.containsPropertyKey(prop.getProperty())) {
+ Class<?> clazz = prop.getClazz();
+ if (!ArrayList.class.getName().equals(clazz.getName())
+ && !HashMap.class.getName().equals(clazz.getName())) {
+ propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make();
+ }
+ } else {
+ propKey = graphMgt.getPropertyKey(prop.getProperty());
+ }
+ if (prop.isIndexed()) {
+ if (!graphMgt.containsGraphIndex(prop.getProperty())) {
+ if (prop.isUnique()) {
+ index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique()
+ .buildCompositeIndex();
+
+ graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures
+ // only
+ // one
+ // name
+ // per
+ // vertex
+ graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures
+ // name
+ // uniqueness
+ // in
+ // the
+ // graph
+
+ } else {
+ graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex();
+ }
+ }
+ }
+ }
+ graphMgt.commit();
+ logger.info("** createVertexIndixes ended");
+ return TitanOperationStatus.OK;
+ }
+ logger.info("** createVertexIndixes ended, no Indixes were created.");
+ return TitanOperationStatus.NOT_CREATED;
+ }
+
+ private TitanOperationStatus createEdgeIndixes() {
+ logger.info("** createEdgeIndixes started");
+ if (graph != null) {
+ // TitanManagement graphMgt = graph.getManagementSystem();
+ TitanManagement graphMgt = graph.openManagement();
+ for (GraphEdgePropertiesDictionary prop : GraphEdgePropertiesDictionary.values()) {
+ if (!graphMgt.containsGraphIndex(prop.getProperty())) {
+ PropertyKey propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make();
+ graphMgt.buildIndex(prop.getProperty(), Edge.class).addKey(propKey).buildCompositeIndex();
+
+ }
+ }
+ graphMgt.commit();
+ logger.info("** createEdgeIndixes ended");
+ return TitanOperationStatus.OK;
+ }
+ logger.info("** createEdgeIndixes ended, no Indixes were created.");
+ return TitanOperationStatus.NOT_CREATED;
+ }
+
+ public TitanOperationStatus commit() {
+ if (graph != null) {
+ try {
+ graph.tx().commit();
+ return TitanOperationStatus.OK;
+ } catch (Exception e) {
+ return handleTitanException(e);
+ }
+ } else {
+ return TitanOperationStatus.NOT_CREATED;
+ }
+ }
+
+ public TitanOperationStatus rollback() {
+ if (graph != null) {
+ try {
+ // graph.rollback();
+ graph.tx().rollback();
+ return TitanOperationStatus.OK;
+ } catch (Exception e) {
+ return handleTitanException(e);
+ }
+ } else {
+ return TitanOperationStatus.NOT_CREATED;
+ }
+ }
+
+ public static TitanOperationStatus handleTitanException(Exception e) {
+ if (e instanceof TitanConfigurationException) {
+ return TitanOperationStatus.TITAN_CONFIGURATION;
+ }
+ if (e instanceof SchemaViolationException) {
+ return TitanOperationStatus.TITAN_SCHEMA_VIOLATION;
+ }
+ if (e instanceof PermanentLockingException) {
+ return TitanOperationStatus.TITAN_SCHEMA_VIOLATION;
+ }
+ if (e instanceof IDPoolExhaustedException) {
+ return TitanOperationStatus.GENERAL_ERROR;
+ }
+ if (e instanceof InvalidElementException) {
+ return TitanOperationStatus.INVALID_ELEMENT;
+ }
+ if (e instanceof InvalidIDException) {
+ return TitanOperationStatus.INVALID_ID;
+ }
+ if (e instanceof QueryException) {
+ return TitanOperationStatus.INVALID_QUERY;
+ }
+ if (e instanceof ResourceUnavailableException) {
+ return TitanOperationStatus.RESOURCE_UNAVAILABLE;
+ }
+ if (e instanceof IllegalArgumentException) {
+ // TODO check the error message??
+ return TitanOperationStatus.ILLEGAL_ARGUMENT;
+ }
+
+ return TitanOperationStatus.GENERAL_ERROR;
+ }
+
+ public boolean getHealth() {
+ return this.lastHealthState;
+ }
+
+ private boolean isGraphOpen() {
+ healthLogger.trace("Invoking Titan health check ...");
+ Vertex v = null;
+ if (graph != null) {
+ try {
+ Future<Vertex> future = healthCheckExecutor.submit(healthCallableTask);
+ v = future.get(this.healthCheckReadTimeout, TimeUnit.SECONDS);
+ healthLogger.trace("Health Check Node Found... " + v.property(HEALTH_CHECK));
+ graph.tx().commit();
+ } catch (Exception e) {
+ String message = e.getMessage();
+ if (message == null) {
+ message = e.getClass().getName();
+ }
+ logger.error("Titan Health Check Failed. " + message);
+ return false;
+ }
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private TitanOperationStatus createCategories() {
+ logger.info("** createCategories started");
+ if (graph != null) {
+ try {
+ List<CategoryData> categoryDataList = getDefaultResourceCategoryList();
+ generateGraphCategories(categoryDataList, NodeTypeEnum.ResourceCategory.getName());
+ } catch (Exception e) {
+ logger.error("createCategories : failed to load categories ", e);
+ rollback();
+ return TitanOperationStatus.GENERAL_ERROR;
+ } finally {
+ logger.info("** createCategories ended");
+ commit();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private void generateGraphCategories(List<CategoryData> categoryDataList, String label) {
+ for (CategoryData categoryData : categoryDataList) {
+ Map<String, Object> properties = categoryData.toGraphMap();
+ properties.put(GraphPropertiesDictionary.LABEL.getProperty(), label);
+
+ // This is temporary for old mechnism of categories - they don;t
+ // have the norm name
+ properties.remove(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty());
+
+ if (isVertexExist(properties)) {
+ return;
+ }
+
+ Vertex vertex = graph.addVertex();
+ for (Map.Entry<String, Object> entry : properties.entrySet()) {
+ vertex.property(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+
+ private List<CategoryData> getDefaultResourceCategoryList() {
+ Map<String, List<String>> categories = new HashMap<String, List<String>>();
+ categories.put("Network Layer 2-3", Arrays.asList("Router", "Gateway", "WAN Connectors", "LAN Connectors"));
+ categories.put("Network Layer 4+", Arrays.asList("Common Network Resources"));
+ categories.put("Application Layer 4+", Arrays.asList("Border Elements", "Application Servers", "Web Server",
+ "Call Control", "Media Servers", "Load Balancer", "Database"));
+ categories.put("Generic", Arrays.asList("Infrastructure", "Abstract", "Network Elements", "Database"));
+
+ List<CategoryData> categoryDataList = new ArrayList<CategoryData>();
+ CategoryData categoryData = null;
+ for (Map.Entry<String, List<String>> entryList : categories.entrySet()) {
+ for (String val : entryList.getValue()) {
+ categoryData = new ResourceCategoryData(entryList.getKey(), val);
+ categoryData.setAction(ActionEnum.Create);
+ categoryData.setElementType(GraphElementTypeEnum.Node);
+ // categoryData.setCategoryName();
+ // categoryData.setName();
+ categoryDataList.add(categoryData);
+ }
+ }
+ return categoryDataList;
+ }
+
+ private List<CategoryData> getDefaultServiceCategoryList() {
+ List<String> categories = new ArrayList<>();
+ categories.add("Mobility");
+ categories.add("Network L1-3");
+ categories.add("Network L4");
+ categories.add("VoIP Call Control");
+
+ List<CategoryData> categoryDataList = new ArrayList<CategoryData>();
+ CategoryData categoryData = null;
+ for (String category : categories) {
+ categoryData = new ServiceCategoryData(category);
+ categoryData.setAction(ActionEnum.Create);
+ categoryData.setElementType(GraphElementTypeEnum.Node);
+ // categoryData.setCategoryName(entryList.getKey());
+ // categoryData.setName(val);
+ categoryDataList.add(categoryData);
+ }
+ return categoryDataList;
+ }
+
+ private void createDefaultUsers() {
+ if (graph != null) {
+ List<UserData> users = createUserList();
+ for (UserData user : users) {
+ String propertyName = GraphPropertiesDictionary.USER_ID.getProperty();
+ String propertyValue = user.getUserId();
+ Vertex vertex = null;
+ Map<String, Object> properties = null;
+ if (!isVertexExist(propertyName, propertyValue)) {
+ vertex = graph.addVertex();
+ vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName());
+ properties = user.toGraphMap();
+ for (Map.Entry<String, Object> entry : properties.entrySet()) {
+ vertex.property(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+ graph.tx().commit();
+ }
+ }
+
+ private List<UserData> createUserList() {
+ LinkedList<UserData> users = new LinkedList<UserData>();
+ users.add(getDefaultUserAdmin1());
+ users.add(getDefaultUserAdmin2());
+ users.add(getDefaultUserAdmin3());
+ users.add(getDefaultUserDesigner1());
+ users.add(getDefaultUserDesigner2());
+ users.add(getDefaultUserDesigner3());
+ users.add(getDefaultUserTester1());
+ users.add(getDefaultUserTester2());
+ users.add(getDefaultUserTester3());
+ users.add(getDefaultUserGovernor1());
+ users.add(getDefaultUserOps1());
+ users.add(getDefaultUserProductManager1());
+ users.add(getDefaultUserProductManager2());
+ users.add(getDefaultUserProductStrategist1());
+ users.add(getDefaultUserProductStrategist2());
+ users.add(getDefaultUserProductStrategist3());
+ return users;
+ }
+
+ private boolean isVertexExist(String propertyName, String propertyValue) {
+ // Iterable<Vertex> vertecies = graph.getVertices(propertyName,
+ // propertyValue);
+ // java.util.Iterator<Vertex> iterator = vertecies.iterator();
+
+ @SuppressWarnings("unchecked")
+ Iterable<TitanVertex> vertecies = graph.query().has(HEALTH_CHECK, OK).vertices();
+
+ java.util.Iterator<TitanVertex> iterator = vertecies.iterator();
+ if (iterator.hasNext()) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isVertexExist(Map<String, Object> properties) {
+ TitanGraphQuery query = graph.query();
+
+ if (properties != null && !properties.isEmpty()) {
+ for (Map.Entry<String, Object> entry : properties.entrySet()) {
+ query = query.has(entry.getKey(), entry.getValue());
+ }
+ }
+ Iterable<Vertex> vertecies = query.vertices();
+ java.util.Iterator<Vertex> iterator = vertecies.iterator();
+ if (iterator.hasNext()) {
+ return true;
+ }
+ return false;
+ }
+
+ private UserData getDefaultUserAdmin1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("jh0003");
+ userData.setEmail("admin@sdc.com");
+ userData.setFirstName("Jimmy");
+ userData.setLastName("Hendrix");
+ userData.setRole("ADMIN");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserAdmin2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("tr0001");
+ userData.setEmail("admin@sdc.com");
+ userData.setFirstName("Todd");
+ userData.setLastName("Rundgren");
+ userData.setRole("ADMIN");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserAdmin3() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("ah0002");
+ userData.setEmail("admin@sdc.com");
+ userData.setFirstName("Alex");
+ userData.setLastName("Harvey");
+ userData.setRole("ADMIN");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserDesigner1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("cs0008");
+ userData.setEmail("designer@sdc.com");
+ userData.setFirstName("Carlos");
+ userData.setLastName("Santana");
+ userData.setRole("DESIGNER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserDesigner2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("me0009");
+ userData.setEmail("designer@sdc.com");
+ userData.setFirstName("Melissa");
+ userData.setLastName("Etheridge");
+ userData.setRole("DESIGNER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserDesigner3() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("af0006");
+ userData.setEmail("designer@sdc.com");
+ userData.setFirstName("Aretha");
+ userData.setLastName("Franklin");
+ userData.setRole("DESIGNER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserTester1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("jm0007");
+ userData.setEmail("tester@sdc.com");
+ userData.setFirstName("Joni");
+ userData.setLastName("Mitchell");
+ userData.setRole("TESTER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserTester2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("kb0004");
+ userData.setEmail("tester@sdc.com");
+ userData.setFirstName("Kate");
+ userData.setLastName("Bush");
+ userData.setRole("TESTER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserTester3() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("jt0005");
+ userData.setEmail("tester@sdc.com");
+ userData.setFirstName("James");
+ userData.setLastName("Taylor");
+ userData.setRole("TESTER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserOps1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("op0001");
+ userData.setEmail("ops@sdc.com");
+ userData.setFirstName("Steve");
+ userData.setLastName("Regev");
+ userData.setRole("OPS");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserGovernor1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("gv0001");
+ userData.setEmail("governor@sdc.com");
+ userData.setFirstName("David");
+ userData.setLastName("Shadmi");
+ userData.setRole("GOVERNOR");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserProductManager1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("pm0001");
+ userData.setEmail("pm1@sdc.com");
+ userData.setFirstName("Teddy");
+ userData.setLastName("Isashar");
+ userData.setRole("PRODUCT_MANAGER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserProductManager2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("pm0002");
+ userData.setEmail("pm2@sdc.com");
+ userData.setFirstName("Sarah");
+ userData.setLastName("Bettens");
+ userData.setRole("PRODUCT_MANAGER");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserProductStrategist1() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("ps0001");
+ userData.setEmail("ps1@sdc.com");
+ userData.setFirstName("Eden");
+ userData.setLastName("Rozin");
+ userData.setRole("PRODUCT_STRATEGIST");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserProductStrategist2() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("ps0002");
+ userData.setEmail("ps2@sdc.com");
+ userData.setFirstName("Ella");
+ userData.setLastName("Kvetny");
+ userData.setRole("PRODUCT_STRATEGIST");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ private UserData getDefaultUserProductStrategist3() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("ps0003");
+ userData.setEmail("ps3@sdc.com");
+ userData.setFirstName("Geva");
+ userData.setLastName("Alon");
+ userData.setRole("PRODUCT_STRATEGIST");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+ public static void main(String[] args) throws InterruptedException {
+ TitanGraphClient client = new TitanGraphClient();
+ client.createGraph();
+
+ while (true) {
+ boolean health = client.isGraphOpen();
+ System.err.println("health=" + health);
+ Thread.sleep(2000);
+ }
+
+ }
+
+ private static final String TITAN_HEALTH_CHECK_STR = "titanHealthCheck";
+
+ private void logAlarm() {
+ if (lastHealthState == true) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckRecovery,
+ TITAN_HEALTH_CHECK_STR);
+ BeEcompErrorManager.getInstance().logBeHealthCheckTitanRecovery(TITAN_HEALTH_CHECK_STR);
+ } else {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckError,
+ TITAN_HEALTH_CHECK_STR);
+ BeEcompErrorManager.getInstance().logBeHealthCheckTitanError(TITAN_HEALTH_CHECK_STR);
+ }
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanOperationStatus.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanOperationStatus.java
new file mode 100644
index 0000000000..dc9ed02fca
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanOperationStatus.java
@@ -0,0 +1,26 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.titan;
+
+public enum TitanOperationStatus {
+ OK, NOT_CONNECTED, NOT_CREATED, INDEX_CANNOT_BE_CHANGED, NOT_FOUND, MISSING_UNIQUE_ID, MISSING_NODE_LABEL, MULTIPLE_EDGES_WITH_SAME_LABEL, CANNOT_DELETE_NON_LEAF_NODE, MULTIPLE_NODES_WITH_SAME_ID, GRAPH_IS_NOT_AVAILABLE, TITAN_CONFIGURATION, TITAN_SCHEMA_VIOLATION, INVALID_ELEMENT, INVALID_QUERY, INVALID_ID, RESOURCE_UNAVAILABLE, ILLEGAL_ARGUMENT, ALREADY_LOCKED, ALREADY_EXIST, MULTIPLE_CHILDS_WITH_SAME_EDGE, GENERAL_ERROR, MATCH_NOT_FOUND, INVALID_TYPE, PROPERTY_NAME_ALREADY_EXISTS, INVALID_PROPERTY,
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/CollectionUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/CollectionUtils.java
new file mode 100644
index 0000000000..7177e4c9fa
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/CollectionUtils.java
@@ -0,0 +1,125 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+public final class CollectionUtils {
+ private CollectionUtils() {
+ }
+
+ /**
+ * Add the content of the 'source' Set to the 'target' set and return the
+ * union set.
+ *
+ * If 'source' is null then a new set is created and returned. If 'target'
+ * is null then no content is added to the 'source' Set or newly created
+ * set.
+ *
+ * @param source
+ * The Set to merge in the target Set.
+ * @param target
+ * The Set in which the source set will be merged (through
+ * addAll).
+ * @return The target Set with addition of source Set elements, or a new Set
+ * (including content of source set) if target was null.
+ */
+ public static <T> Set<T> merge(Set<T> source, Set<T> target) {
+ Set<T> merged = new HashSet<T>();
+ if (target != null) {
+ merged.addAll(target);
+ }
+ if (source != null) {
+ merged.addAll(source);
+ }
+ return merged.isEmpty() ? null : merged;
+ }
+
+ /**
+ * <p>
+ * Add the content of the 'source' Map to the 'target' set and return the
+ * union Map.
+ * </p>
+ * <p>
+ * If 'source' is null then a new Map is created and returned. If 'target'
+ * is null then no content is added to the 'source' Map or newly created
+ * Map.
+ * </p>
+ *
+ * @param source
+ * The Map to merge in the target Map.
+ * @param target
+ * The Map in which the source Map will be merged (through
+ * addAll).
+ * @param override
+ * If an key from the source map already exists in the target
+ * map, should it override (true) or not (false) the value.
+ * @return The target Map with addition of source Map elements, or a new Map
+ * (including content of source set) if target was null.
+ */
+ public static <T, V> Map<T, V> merge(Map<T, ? extends V> source, Map<T, V> target, boolean override) {
+ if (target == null) {
+ target = new HashMap();
+ }
+
+ if (source != null) {
+ for (Entry<T, ? extends V> entry : source.entrySet()) {
+ if (override || !target.containsKey(entry.getKey())) {
+ target.put(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+ return target.isEmpty() ? null : target;
+ }
+
+ /**
+ * Merge two lists, the merge is performed based on the contains method so
+ * elements presents both in source and target are not added twice to the
+ * list.
+ *
+ * @param source
+ * The source list.
+ * @param target
+ * The target list.
+ * @return A list that represents the merged collections.
+ */
+ public static <T> List<T> merge(List<T> source, List<T> target) {
+ List<T> merged = target == null ? new ArrayList<T>() : target;
+
+ if (source == null) {
+ return merged;
+ }
+
+ for (T t : source) {
+ if (!merged.contains(t)) {
+ merged.add(t);
+ }
+ }
+
+ return merged;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/Constants.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/Constants.java
new file mode 100644
index 0000000000..4487e51a55
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/Constants.java
@@ -0,0 +1,38 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+/**
+ * Holds constants to use in ALIEN.
+ */
+public final class Constants {
+ public static final int DEFAULT_ES_SEARCH_SIZE = 50;
+ public static final int MAX_ES_SEARCH_SIZE = 100;
+
+ public static final String ALIEN_INTERNAL_TAG = "icon";
+ public static final String DEFAULT_CAPABILITY_FIELD_NAME = "defaultCapabilities";
+
+ public static final String GROUP_NAME_ALL_USERS = "ALL_USERS";
+ public static final String GRAPH_EMPTY_VALUE = "__NANANA__";
+
+ private Constants() {
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/DaoUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/DaoUtils.java
new file mode 100644
index 0000000000..b21d1e9630
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/DaoUtils.java
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+import com.google.gson.Gson;
+
+/**
+ *
+ * @author Evgenia Alberstein
+ *
+ * Utility class for convertation to/from JSON string
+ */
+public class DaoUtils {
+
+ /**
+ * Convert from Object to Json string
+ *
+ * @param object
+ * @return json string
+ */
+ public static String convertToJson(Object object) {
+ if (object == null) {
+ throw new RuntimeException("The object cannot be NULL!!!");
+ }
+ Gson gson = new Gson(); // Or use new GsonBuilder().create();
+ return gson.toJson(object); // serializes target to Json
+ }
+
+ /**
+ * Convert from Json string to object
+ *
+ * @param clazz
+ * @param json
+ * @return object
+ */
+ public static <T> T convertFromJson(Class<T> clazz, String json) {
+ Gson gson = new Gson(); // Or use new GsonBuilder().create();
+ return gson.fromJson(json, clazz); // deserializes json into target2
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ElasticSearchUtil.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ElasticSearchUtil.java
new file mode 100644
index 0000000000..f20b523a4d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ElasticSearchUtil.java
@@ -0,0 +1,48 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+import org.elasticsearch.action.search.SearchResponse;
+
+/**
+ * Utility class to work with elastic search responses.
+ *
+ */
+public final class ElasticSearchUtil {
+ private ElasticSearchUtil() {
+ }
+
+ /**
+ * Checks if a search response from elastic search contains results or not.
+ *
+ * @param searchResponse
+ * The ES search response object.
+ * @return True if the response does not contain any result, false if the
+ * response does contains results.
+ */
+ public static boolean isResponseEmpty(SearchResponse searchResponse) {
+ if (searchResponse == null || searchResponse.getHits() == null || searchResponse.getHits().getHits() == null
+ || searchResponse.getHits().getHits().length == 0) {
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/Exceptions.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/Exceptions.java
new file mode 100644
index 0000000000..fd0a6754ab
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/Exceptions.java
@@ -0,0 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+public final class Exceptions {
+ private Exceptions() {
+ }
+
+ public static RuntimeException convertToRuntimeEx(Throwable t) {
+ return Exceptions.<RuntimeException>convertToRTException(t);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static <T extends Throwable> T convertToRTException(Throwable t) throws T {
+ throw (T) t;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageQuality.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageQuality.java
new file mode 100644
index 0000000000..4eb691a4b7
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageQuality.java
@@ -0,0 +1,40 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+/**
+ * Available qualities for images in Alien 4 Cloud.
+ *
+ * @author luc boutier
+ */
+public enum ImageQuality {
+ QUALITY_16(16), QUALITY_32(32), QUALITY_64(64), QUALITY_128(128), QUALITY_512(512), QUALITY_BEST(-1);
+
+ private final int size;
+
+ private ImageQuality(int size) {
+ this.size = size;
+ }
+
+ public int getSize() {
+ return size;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageResizeUtil.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageResizeUtil.java
new file mode 100644
index 0000000000..4db8c72e5a
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageResizeUtil.java
@@ -0,0 +1,142 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+import java.awt.Graphics2D;
+import java.awt.Image;
+import java.awt.RenderingHints;
+import java.awt.image.BufferedImage;
+
+/**
+ * Utility to resize images.
+ *
+ * @author luc boutier
+ */
+public final class ImageResizeUtil {
+ private ImageResizeUtil() {
+ }
+
+ /**
+ * Resize an image with default quality settings.
+ *
+ * @param originalImage
+ * The image to resize.
+ * @param width
+ * The target width.
+ * @param height
+ * The target height.
+ * @param preserveDimensions
+ * Flag to know if we should preserve original image dimensions.
+ * @return The resized image.
+ */
+ public static BufferedImage resizeImage(final BufferedImage originalImage, final int width, final int height,
+ final boolean preserveDimensions) {
+ return resizeImage(originalImage, width, height, preserveDimensions, false);
+ }
+
+ /**
+ * <p>
+ * Resize an image with high quality settings.
+ * </p>
+ * <ul>
+ * <li>g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
+ * RenderingHints.VALUE_INTERPOLATION_BILINEAR);</li>
+ * <li>g.setRenderingHint(RenderingHints.KEY_RENDERING,
+ * RenderingHints.VALUE_RENDER_QUALITY);</li>
+ * <li>g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ * RenderingHints.VALUE_ANTIALIAS_ON);</li>
+ * </ul>
+ *
+ * @param originalImage
+ * The image to resize.
+ * @param width
+ * The target width.
+ * @param height
+ * The target height.
+ * @param preserveDimensions
+ * Flag to know if we should preserve original image dimensions.
+ * @return The resized image.
+ */
+ public static BufferedImage resizeImageWithHint(BufferedImage originalImage, final int width, final int height,
+ final boolean preserveDimensions) {
+ return resizeImage(originalImage, width, height, preserveDimensions, true);
+ }
+
+ private static BufferedImage resizeImage(BufferedImage originalImage, final int width, final int height,
+ final boolean preserveDimensions, final boolean enableHighQuality) {
+ int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
+
+ int targetWidth = width;
+ int targetHeight = height;
+
+ if (preserveDimensions) {
+ int[] targetDimentions = computeDimensions(width, height, originalImage.getWidth(),
+ originalImage.getHeight());
+ targetWidth = targetDimentions[0];
+ targetHeight = targetDimentions[1];
+ }
+
+ BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, type);
+
+ Graphics2D g = resizedImage.createGraphics();
+ if (enableHighQuality) {
+ g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
+ g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
+ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ }
+
+ g.drawImage(originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH), 0, 0, null);
+ g.dispose();
+
+ return resizedImage;
+ }
+
+ /**
+ * Compute target width and height based on requested width and height but
+ * making sure the original dimensions of the image will be preserved.
+ *
+ * @param width
+ * The ideal (and max) target width.
+ * @param height
+ * The ideal (and max) target height.
+ * @param originalWidth
+ * The original width.
+ * @param originalHeight
+ * The original height.
+ * @return An array of int that contains the ideal width and height to
+ * preserve dimensions.
+ */
+ public static int[] computeDimensions(final int width, final int height, final int originalWidth,
+ final int originalHeight) {
+ int targetWidth = width;
+ int targetHeight = height;
+
+ float targetDimensions = Float.valueOf(width).floatValue() / Float.valueOf(height).floatValue();
+ float sourceDimensions = Float.valueOf(originalWidth).floatValue() / Float.valueOf(originalHeight).floatValue();
+ if (targetDimensions > sourceDimensions) {
+ targetWidth = Float.valueOf(width * sourceDimensions / targetDimensions).intValue();
+ } else {
+ targetHeight = Float.valueOf(height * targetDimensions / sourceDimensions).intValue();
+ }
+
+ return new int[] { targetWidth, targetHeight };
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/JsonUtil.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/JsonUtil.java
new file mode 100644
index 0000000000..00b6d5e894
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/JsonUtil.java
@@ -0,0 +1,209 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+
+/**
+ * Simple utility for JSon processing.
+ */
+public final class JsonUtil {
+ private static ObjectMapper getOneObjectMapper() {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.INDENT_OUTPUT);
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+ mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
+ return mapper;
+ }
+
+ private JsonUtil() {
+ }
+
+ // /**
+ // * Parse a {@link RestResponse} by using the specified dataType as the
+ // expected data object's class.
+ // *
+ // * @param responseAsString
+ // * The {@link RestResponse} as a JSon String
+ // * @param dataType
+ // * The type of the data object.
+ // * @return The parsed {@link RestResponse} object matching the given JSon.
+ // * @throws JsonParseException
+ // * In case of a JSon parsing issue.
+ // * @throws JsonMappingException
+ // * In case of a JSon parsing issue.
+ // * @throws IOException
+ // * In case of an IO error.
+ // */
+ // public static <T> RestResponse<T> read(String responseAsString, Class<T>
+ // dataType) throws IOException {
+ // ObjectMapper mapper = getOneObjectMapper();
+ // JavaType restResponseType =
+ // mapper.getTypeFactory().constructParametricType(RestResponse.class,
+ // dataType);
+ // return mapper.readValue(responseAsString, restResponseType);
+ // }
+
+ /**
+ * Deserialize json text to object
+ *
+ * @param objectText
+ * @param objectClass
+ * @return
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ public static <T> T readObject(String objectText, Class<T> objectClass) throws IOException {
+ return getOneObjectMapper().readValue(objectText, objectClass);
+ }
+
+ /**
+ * Deserialize json stream to object
+ *
+ * @param jsonStream
+ * @param objectClass
+ * @return
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ public static <T> T readObject(InputStream jsonStream, Class<T> objectClass) throws IOException {
+ return getOneObjectMapper().readValue(jsonStream, objectClass);
+ }
+
+ /**
+ * Deserialize json text to object
+ *
+ * @param objectText
+ * @return
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ public static <T> T readObject(String objectText) throws IOException {
+ TypeReference<T> typeRef = new TypeReference<T>() {
+ };
+ return getOneObjectMapper().readValue(objectText, typeRef);
+ }
+
+ // /**
+ // * Parse a {@link RestResponse} without being interested in parameterized
+ // type
+ // *
+ // * @param responseAsString
+ // * @return
+ // * @throws JsonParseException
+ // * @throws JsonMappingException
+ // * @throws IOException
+ // */
+ // public static RestResponse<?> read(String responseAsString) throws
+ // IOException {
+ // return getOneObjectMapper().readValue(responseAsString,
+ // RestResponse.class);
+ // }
+
+ // /**
+ // * Serialize the given object in a JSon String.
+ // *
+ // * @param obj
+ // * The object to serialize.
+ // * @return The JSon serialization of the given object.
+ // * @throws JsonProcessingException
+ // * In case of a failure in serialization.
+ // */
+ // public static String toString(Object obj) throws JsonProcessingException
+ // {
+ // return getOneObjectMapper().writeValueAsString(obj);
+ // }
+
+ /**
+ * Deserialize the given json string to a map
+ *
+ * @param json
+ * json text
+ * @return map object
+ * @throws IOException
+ */
+ public static Map<String, Object> toMap(String json) throws IOException {
+ ObjectMapper mapper = getOneObjectMapper();
+ JavaType mapStringObjectType = mapper.getTypeFactory().constructParametricType(HashMap.class, String.class,
+ Object.class);
+ return mapper.readValue(json, mapStringObjectType);
+ }
+
+ /**
+ * Deserialize the given json string to a map
+ *
+ * @param json
+ * @param keyTypeClass
+ * @param valueTypeClass
+ * @return
+ * @throws IOException
+ */
+ public static <K, V> Map<K, V> toMap(String json, Class<K> keyTypeClass, Class<V> valueTypeClass)
+ throws IOException {
+ ObjectMapper mapper = getOneObjectMapper();
+ JavaType mapStringObjectType = mapper.getTypeFactory().constructParametricType(HashMap.class, keyTypeClass,
+ valueTypeClass);
+ return mapper.readValue(json, mapStringObjectType);
+ }
+
+ public static <V> V[] toArray(String json, Class<V> valueTypeClass) throws IOException {
+ ObjectMapper mapper = getOneObjectMapper();
+ JavaType arrayStringObjectType = mapper.getTypeFactory().constructArrayType(valueTypeClass);
+ return mapper.readValue(json, arrayStringObjectType);
+ }
+
+ /**
+ * Deserialize the given json string to a list
+ *
+ * @param json
+ * json text
+ * @return list object
+ * @throws IOException
+ */
+ public static <T> List<T> toList(String json, Class<T> clazz) throws IOException {
+ ObjectMapper mapper = getOneObjectMapper();
+ JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, clazz);
+ return mapper.readValue(json, type);
+ }
+
+ public static <T> List<T> toList(String json, Class<T> elementClass, Class<?> elementGenericClass)
+ throws IOException {
+ ObjectMapper mapper = getOneObjectMapper();
+ JavaType elementType = mapper.getTypeFactory().constructParametricType(elementClass, elementGenericClass);
+ JavaType listType = mapper.getTypeFactory().constructCollectionType(List.class, elementType);
+ return mapper.readValue(json, listType);
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapEntry.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapEntry.java
new file mode 100644
index 0000000000..13561f60a0
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapEntry.java
@@ -0,0 +1,55 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+/**
+ * A map/set entry as a key/value object to be serialized as is.
+ *
+ * @author luc boutier
+ */
+public class MapEntry<T, V> {
+ private T key;
+ private V value;
+
+ public MapEntry() {
+ }
+
+ public MapEntry(T key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ public T getKey() {
+ return key;
+ }
+
+ public void setKey(T key) {
+ this.key = key;
+ }
+
+ public V getValue() {
+ return value;
+ }
+
+ public void setValue(V value) {
+ this.value = value;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java
new file mode 100644
index 0000000000..84802ce293
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java
@@ -0,0 +1,86 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Utility class to ease map manipulation.
+ */
+public final class MapUtil {
+ private MapUtil() {
+ }
+
+ /**
+ * Try to get a value following a path in the map. For example :
+ * MapUtil.get(map, "a.b.c") correspond to: map.get(a).get(b).get(c)
+ *
+ * @param map
+ * the map to search for path
+ * @param path
+ * keys in the map separated by '.'
+ */
+ public static Object get(Map<String, ? extends Object> map, String path) {
+ String[] tokens = path.split("\\.");
+ if (tokens.length == 0) {
+ return null;
+ } else {
+ Object value = map;
+ for (String token : tokens) {
+ if (!(value instanceof Map)) {
+ return null;
+ } else {
+ @SuppressWarnings("unchecked")
+ Map<String, Object> nested = (Map<String, Object>) value;
+ if (nested.containsKey(token)) {
+ value = nested.get(token);
+ } else {
+ return null;
+ }
+ }
+ }
+ return value;
+ }
+ }
+
+ /**
+ * Create a new hash map and fills it from the given keys and values
+ * (keys[index] -> values[index].
+ *
+ * @param keys
+ * The array of keys.
+ * @param values
+ * The array of values.
+ * @return A map that contains for each key element in the keys array a
+ * value from the values array at the same index.
+ */
+ public static <K, V> Map<K, V> newHashMap(K[] keys, V[] values) {
+ Map<K, V> map = new HashMap<K, V>();
+ if (keys == null || values == null || keys.length != values.length) {
+ throw new IllegalArgumentException("keys and values must be non-null and have the same size.");
+ }
+ for (int i = 0; i < keys.length; i++) {
+ map.put(keys[i], values[i]);
+ }
+ return map;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/TypeMap.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/TypeMap.java
new file mode 100644
index 0000000000..1f7e692598
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/TypeMap.java
@@ -0,0 +1,63 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class TypeMap {
+ private Map<Class<? extends Object>, Map<String, Object>> cacheMap = new HashMap<Class<? extends Object>, Map<String, Object>>();
+
+ private Map<String, Object> getMap(Class<? extends Object> clazz) {
+ Map<String, Object> map = cacheMap.get(clazz);
+ if (map == null) {
+ cacheMap.put(clazz, new HashMap<String, Object>());
+ }
+ return cacheMap.get(clazz);
+ }
+
+ /**
+ * put an object (value) in it's type map using the given key.
+ *
+ * @param key
+ * The key inside the type map.
+ * @param value
+ * The object to insert (based on it's type and the given key).
+ */
+ public void put(String key, Object value) {
+ getMap(value.getClass()).put(key, value);
+ }
+
+ /**
+ * Get the cached object based on it's type and key.
+ *
+ * @param clazz
+ * The object's type.
+ * @param key
+ * The object key.
+ * @return The object that match the given type and key or null if none
+ * matches.
+ */
+ @SuppressWarnings("unchecked")
+ public <T> T get(Class<T> clazz, String key) {
+ return (T) (cacheMap.get(clazz) == null ? null : cacheMap.get(clazz).get(key));
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/UserStatusEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/UserStatusEnum.java
new file mode 100644
index 0000000000..dbe9b84a5e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/UserStatusEnum.java
@@ -0,0 +1,40 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.dao.utils;
+
+import org.openecomp.sdc.common.util.MethodActivationStatusEnum;
+
+import fj.data.Either;
+
+public enum UserStatusEnum {
+ ACTIVE, INACTIVE;
+
+ public static Either<UserStatusEnum, MethodActivationStatusEnum> findByName(String name) {
+ Either<UserStatusEnum, MethodActivationStatusEnum> result = Either.right(MethodActivationStatusEnum.NOT_FOUND);
+ for (UserStatusEnum status : UserStatusEnum.values()) {
+ if (status.name().equals(name)) {
+ result = Either.left(status);
+ break;
+ }
+ }
+ return result;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/ArtifactDataEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/ArtifactDataEnum.java
new file mode 100644
index 0000000000..39c023dc00
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/ArtifactDataEnum.java
@@ -0,0 +1,26 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.api;
+
+public enum ArtifactDataEnum {
+ SERVICE_ARTIFACT, COMPONENT_ARTIFACT
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/IResourceUploader.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/IResourceUploader.java
new file mode 100644
index 0000000000..9eea2962e1
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/IResourceUploader.java
@@ -0,0 +1,76 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.api;
+
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.api.ResourceUploadStatus;
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.be.resources.data.ServiceArtifactsDataCollection;
+import org.openecomp.sdc.be.resources.exception.ResourceDAOException;
+
+import fj.data.Either;
+
+/**
+ * DAO to manage image upload and retrieval.
+ *
+ * @author luc boutier
+ */
+public interface IResourceUploader {
+
+ /**
+ * Save an artifact in the DAO layer.
+ *
+ * @param imageData
+ */
+ ResourceUploadStatus saveArtifact(ESArtifactData artifactData, boolean isReload);
+
+ /**
+ * Save an artifact in the DAO layer.
+ *
+ * @param imageData
+ */
+ ResourceUploadStatus updateArtifact(ESArtifactData artifactData);
+
+ /**
+ * Get an artifact as a byte array based on the artifact id.
+ *
+ * @param id
+ * The id of the artifact to read.
+ * @return The artifact as a byte array.
+ */
+ Either<ESArtifactData, ResourceUploadStatus> getArtifact(String id);
+
+ /**
+ * Delete the given image.
+ *
+ * @param id
+ * Id of the image to delete.
+ */
+ void deleteArtifact(String id);
+
+ /**
+ * delete all artifacts
+ */
+ public void deleteAllArtifacts();
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java
new file mode 100644
index 0000000000..a5a6e6df76
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java
@@ -0,0 +1,155 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class AdditionalInfoParameterData extends GraphNode {
+
+ AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition;
+
+ private Map<String, String> parameters;
+
+ private Map<String, String> idToKey;
+
+ public AdditionalInfoParameterData() {
+ super(NodeTypeEnum.AdditionalInfoParameters);
+ additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition();
+ }
+
+ public AdditionalInfoParameterData(AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition,
+ Map<String, String> parameters, Map<String, String> idToKey) {
+ super(NodeTypeEnum.AdditionalInfoParameters);
+ this.additionalInfoParameterDataDefinition = additionalInfoParameterDataDefinition;
+ this.parameters = parameters;
+ this.idToKey = idToKey;
+ }
+
+ public AdditionalInfoParameterData(Map<String, Object> properties) {
+
+ this();
+
+ additionalInfoParameterDataDefinition
+ .setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ additionalInfoParameterDataDefinition
+ .setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ additionalInfoParameterDataDefinition
+ .setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ additionalInfoParameterDataDefinition.setLastCreatedCounter(
+ (Integer) properties.get(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty()));
+ Type mapType = new TypeToken<HashMap<String, String>>() {
+ }.getType();
+ HashMap<String, String> prametersfromJson = getGson().fromJson(
+ (String) properties.get(GraphPropertiesDictionary.ADDITIONAL_INFO_PARAMS.getProperty()), mapType);
+
+ this.setParameters(prametersfromJson);
+
+ // this.setParameters((HashMap<String, String>) properties
+ // .get(GraphPropertiesDictionary.ADDITIONAL_INFO_PARAMS
+ // .getProperty()));
+
+ HashMap<String, String> idToKeyfromJson = getGson().fromJson(
+ (String) properties.get(GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY.getProperty()), mapType);
+
+ this.setIdToKey(idToKeyfromJson);
+ // this.setIdToKey((HashMap<String, String>) properties
+ // .get(GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY
+ // .getProperty()));
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, additionalInfoParameterDataDefinition.getUniqueId());
+
+ // String parametersToJson = getGson().toJson(getParameters());
+
+ // addIfExists(map, GraphPropertiesDictionary.ADDITIONAL_INFO_PARAMS,
+ // parametersToJson);
+ addIfExists(map, GraphPropertiesDictionary.ADDITIONAL_INFO_PARAMS, getParameters());
+
+ // String idToKeyToJson = getGson().toJson(getIdToKey());
+ // addIfExists(map, GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY,
+ // idToKeyToJson);
+ addIfExists(map, GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY, getIdToKey());
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE,
+ additionalInfoParameterDataDefinition.getCreationTime());
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE,
+ additionalInfoParameterDataDefinition.getModificationTime());
+
+ addIfExists(map, GraphPropertiesDictionary.PROPERTY_COUNTER,
+ additionalInfoParameterDataDefinition.getLastCreatedCounter());
+
+ return map;
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return additionalInfoParameterDataDefinition.getUniqueId();
+ }
+
+ public AdditionalInfoParameterDataDefinition getAdditionalInfoParameterDataDefinition() {
+ return additionalInfoParameterDataDefinition;
+ }
+
+ public void setAdditionalInfoParameterDataDefinition(
+ AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition) {
+ this.additionalInfoParameterDataDefinition = additionalInfoParameterDataDefinition;
+ }
+
+ public Map<String, String> getParameters() {
+ return parameters;
+ }
+
+ public void setParameters(Map<String, String> parameters) {
+ this.parameters = parameters;
+ }
+
+ public Map<String, String> getIdToKey() {
+ return idToKey;
+ }
+
+ public void setIdToKey(Map<String, String> idToKey) {
+ this.idToKey = idToKey;
+ }
+
+ @Override
+ public String toString() {
+ return "PropertyData [parameters= " + parameters + " idToKey= " + idToKey
+ + ", additionalInfoParameterDataDefinition=" + additionalInfoParameterDataDefinition + "]";
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java
new file mode 100644
index 0000000000..e4da028c60
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java
@@ -0,0 +1,183 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class ArtifactData extends GraphNode {
+
+ private ArtifactDataDefinition artifactDataDefinition;
+
+ public ArtifactData() {
+ super(NodeTypeEnum.ArtifactRef);
+ artifactDataDefinition = new ArtifactDataDefinition();
+ }
+
+ public ArtifactData(ArtifactDataDefinition artifactDataDefinition) {
+ super(NodeTypeEnum.ArtifactRef);
+ this.artifactDataDefinition = artifactDataDefinition;
+
+ }
+
+ public ArtifactData(Map<String, Object> properties) {
+ this();
+ artifactDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ artifactDataDefinition
+ .setArtifactType((String) properties.get(GraphPropertiesDictionary.ARTIFACT_TYPE.getProperty()));
+ artifactDataDefinition
+ .setArtifactRef((String) properties.get(GraphPropertiesDictionary.ARTIFACT_REF.getProperty()));
+ artifactDataDefinition.setArtifactName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+ artifactDataDefinition.setArtifactRepository(
+ (String) properties.get(GraphPropertiesDictionary.ARTIFACT_REPOSITORY.getProperty()));
+ artifactDataDefinition.setArtifactChecksum(
+ (String) properties.get(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty()));
+ artifactDataDefinition
+ .setArtifactCreator((String) properties.get(GraphPropertiesDictionary.CREATOR.getProperty()));
+ artifactDataDefinition
+ .setUserIdCreator((String) properties.get(GraphPropertiesDictionary.ATT_CREATOR.getProperty()));
+ artifactDataDefinition
+ .setUserIdLastUpdater((String) properties.get(GraphPropertiesDictionary.LAST_UPDATER.getProperty()));
+ artifactDataDefinition
+ .setCreatorFullName((String) properties.get(GraphPropertiesDictionary.CREATOR_FULL_NAME.getProperty()));
+ artifactDataDefinition
+ .setUpdaterFullName((String) properties.get(GraphPropertiesDictionary.UPDATER_FULL_NAME.getProperty()));
+ artifactDataDefinition
+ .setCreationDate((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+ artifactDataDefinition
+ .setLastUpdateDate((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+ artifactDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+ artifactDataDefinition.setEsId((String) properties.get(GraphPropertiesDictionary.ES_ID.getProperty()));
+ artifactDataDefinition
+ .setArtifactLabel((String) properties.get(GraphPropertiesDictionary.ARTIFACT_LABEL.getProperty()));
+ artifactDataDefinition
+ .setMandatory((Boolean) properties.get(GraphPropertiesDictionary.IS_ABSTRACT.getProperty()));
+ artifactDataDefinition.setArtifactChecksum(
+ (String) properties.get(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty()));
+ artifactDataDefinition.setArtifactDisplayName(
+ (String) properties.get(GraphPropertiesDictionary.ARTIFACT_DISPLAY_NAME.getProperty()));
+ artifactDataDefinition.setApiUrl((String) properties.get(GraphPropertiesDictionary.API_URL.getProperty()));
+ artifactDataDefinition
+ .setServiceApi((Boolean) properties.get(GraphPropertiesDictionary.SERVICE_API.getProperty()));
+ artifactDataDefinition
+ .setArtifactVersion((String) properties.get(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty()));
+ artifactDataDefinition
+ .setArtifactUUID((String) properties.get(GraphPropertiesDictionary.ARTIFACT_UUID.getProperty()));
+ artifactDataDefinition.setPayloadUpdateDate(
+ (Long) properties.get(GraphPropertiesDictionary.PAYLOAD_UPDATE_DATE.getProperty()));
+ artifactDataDefinition.setHeatParamsUpdateDate(
+ (Long) properties.get(GraphPropertiesDictionary.HEAT_PARAMS_UPDATE_DATE.getProperty()));
+ artifactDataDefinition.setGenerated((Boolean) properties.get(GraphPropertiesDictionary.GENERATED.getProperty()));
+ Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> requiredArtifactsfromJson = getGson().fromJson(
+ (String) properties.get(GraphPropertiesDictionary.REQUIRED_ARTIFACTS.getProperty()), listType);
+ artifactDataDefinition.setRequiredArtifacts(requiredArtifactsfromJson);
+
+ String groupType = (String) properties.get(GraphPropertiesDictionary.ARTIFACT_GROUP_TYPE.getProperty());
+ if (groupType != null && !groupType.isEmpty()) {
+
+ artifactDataDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.findType(groupType));
+ }
+
+ Integer timeout = (Integer) properties.get(GraphPropertiesDictionary.ARTIFACT_TIMEOUT.getProperty());
+ if (timeout != null) {
+
+ artifactDataDefinition.setTimeout(timeout);
+ }
+
+ }
+
+ public ArtifactDataDefinition getArtifactDataDefinition() {
+ return artifactDataDefinition;
+ }
+
+ public void setArtifactDataDefinition(ArtifactDataDefinition artifactDataDefinition) {
+ this.artifactDataDefinition = artifactDataDefinition;
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return artifactDataDefinition.getUniqueId();
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, artifactDataDefinition.getUniqueId());
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_TYPE, artifactDataDefinition.getArtifactType());
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_REF, artifactDataDefinition.getArtifactRef());
+ addIfExists(map, GraphPropertiesDictionary.NAME, artifactDataDefinition.getArtifactName());
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_REPOSITORY, artifactDataDefinition.getArtifactRepository());
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_CHECKSUM, artifactDataDefinition.getArtifactChecksum());
+ addIfExists(map, GraphPropertiesDictionary.CREATOR, artifactDataDefinition.getArtifactCreator());
+ addIfExists(map, GraphPropertiesDictionary.ATT_CREATOR, artifactDataDefinition.getUserIdCreator());
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATER, artifactDataDefinition.getUserIdLastUpdater());
+ addIfExists(map, GraphPropertiesDictionary.CREATOR_FULL_NAME, artifactDataDefinition.getCreatorFullName());
+ addIfExists(map, GraphPropertiesDictionary.UPDATER_FULL_NAME, artifactDataDefinition.getUpdaterFullName());
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, artifactDataDefinition.getCreationDate());
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, artifactDataDefinition.getLastUpdateDate());
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, artifactDataDefinition.getDescription());
+ addIfExists(map, GraphPropertiesDictionary.ES_ID, artifactDataDefinition.getEsId());
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_LABEL, artifactDataDefinition.getArtifactLabel());
+ addIfExists(map, GraphPropertiesDictionary.IS_ABSTRACT, artifactDataDefinition.getMandatory());
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_CHECKSUM, artifactDataDefinition.getArtifactChecksum());
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_DISPLAY_NAME,
+ artifactDataDefinition.getArtifactDisplayName());
+ addIfExists(map, GraphPropertiesDictionary.API_URL, artifactDataDefinition.getApiUrl());
+ addIfExists(map, GraphPropertiesDictionary.SERVICE_API, artifactDataDefinition.getServiceApi());
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_TIMEOUT, artifactDataDefinition.getTimeout());
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_VERSION, artifactDataDefinition.getArtifactVersion());
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_UUID, artifactDataDefinition.getArtifactUUID());
+ addIfExists(map, GraphPropertiesDictionary.PAYLOAD_UPDATE_DATE, artifactDataDefinition.getPayloadUpdateDate());
+ addIfExists(map, GraphPropertiesDictionary.HEAT_PARAMS_UPDATE_DATE,
+ artifactDataDefinition.getHeatParamsUpdateDate());
+ addIfExists(map, GraphPropertiesDictionary.REQUIRED_ARTIFACTS, artifactDataDefinition.getRequiredArtifacts());
+ addIfExists(map, GraphPropertiesDictionary.GENERATED, artifactDataDefinition.getGenerated());
+
+ String groupType = null;
+ ArtifactGroupTypeEnum groupTypeEnum = artifactDataDefinition.getArtifactGroupType();
+ if (groupTypeEnum != null) {
+ groupType = groupTypeEnum.getType();
+ }
+ addIfExists(map, GraphPropertiesDictionary.ARTIFACT_GROUP_TYPE, groupType);
+
+ return map;
+ }
+
+ @Override
+ public String toString() {
+ return "ArtifactData [artifactDataDefinition=" + artifactDataDefinition + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java
new file mode 100644
index 0000000000..16a8c8be60
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java
@@ -0,0 +1,131 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.Constants;
+import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class AttributeData extends GraphNode {
+ AttributeDataDefinition attributeDataDefinition;
+
+ public AttributeData() {
+ super(NodeTypeEnum.Attribute);
+ attributeDataDefinition = new AttributeDataDefinition();
+ }
+
+ public AttributeData(AttributeDataDefinition attributeDataDefinition) {
+ super(NodeTypeEnum.Attribute);
+ this.attributeDataDefinition = attributeDataDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "AttributeData [attributeDataDefinition=" + attributeDataDefinition + "]";
+ }
+
+ @Override
+ public String getUniqueId() {
+ return attributeDataDefinition.getUniqueId();
+ }
+
+ public AttributeDataDefinition getAttributeDataDefinition() {
+ return attributeDataDefinition;
+ }
+
+ public void setAttributeDataDefinition(AttributeDataDefinition attributeDataDefinition) {
+ this.attributeDataDefinition = attributeDataDefinition;
+ }
+
+ public AttributeData(Map<String, Object> properties) {
+
+ this();
+
+ attributeDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ attributeDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+
+ attributeDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+
+ String defaultValue = (String) properties.get(GraphPropertiesDictionary.DEFAULT_VALUE.getProperty());
+ if (Constants.GRAPH_EMPTY_VALUE.equals(defaultValue)) {
+ attributeDataDefinition.setDefaultValue(null);
+ } else {
+ attributeDataDefinition.setDefaultValue(defaultValue);
+ }
+
+ attributeDataDefinition.setStatus((String) properties.get(GraphPropertiesDictionary.STATUS.getProperty()));
+
+ attributeDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+
+ attributeDataDefinition.setValue((String) properties.get(GraphPropertiesDictionary.VALUE.getProperty()));
+
+ Type schemaType = new TypeToken<SchemaDefinition>() {
+ }.getType();
+ SchemaDefinition schema = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.ENTRY_SCHEMA.getProperty()), schemaType);
+ attributeDataDefinition.setSchema(schema);
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, attributeDataDefinition.getUniqueId());
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, attributeDataDefinition.getType());
+
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, attributeDataDefinition.getDescription());
+
+ String defaultValue = attributeDataDefinition.getDefaultValue();
+ if (defaultValue == null) {
+ defaultValue = Constants.GRAPH_EMPTY_VALUE;
+ }
+
+ addIfExists(map, GraphPropertiesDictionary.DEFAULT_VALUE, defaultValue);
+
+ addIfExists(map, GraphPropertiesDictionary.STATUS, attributeDataDefinition.getStatus());
+
+ addIfExists(map, GraphPropertiesDictionary.NAME, attributeDataDefinition.getName());
+
+ addIfExists(map, GraphPropertiesDictionary.VALUE, attributeDataDefinition.getValue());
+
+ SchemaDefinition entrySchema = attributeDataDefinition.getSchema();
+ if (entrySchema != null) {
+ String entrySchemaStr = getGson().toJson(entrySchema);
+ addIfExists(map, GraphPropertiesDictionary.ENTRY_SCHEMA, entrySchemaStr);
+ }
+
+ return map;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeValueData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeValueData.java
new file mode 100644
index 0000000000..7c8ce1dbb6
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeValueData.java
@@ -0,0 +1,145 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.Constants;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class AttributeValueData extends GraphNode {
+ private String uniqueId;
+
+ private String value;
+
+ private String type;
+
+ private Boolean hidden;
+
+ private Long creationTime;
+
+ private Long modificationTime;
+
+ public AttributeValueData() {
+ super(NodeTypeEnum.AttributeValue);
+ }
+
+ public AttributeValueData(Map<String, Object> properties) {
+ this();
+
+ this.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+
+ String updatedValue = (String) properties.get(GraphPropertiesDictionary.VALUE.getProperty());
+ if (Constants.GRAPH_EMPTY_VALUE.equals(updatedValue)) {
+ this.setValue(null);
+ } else {
+ this.setValue(updatedValue);
+ }
+
+ this.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ this.setHidden((Boolean) properties.get(GraphPropertiesDictionary.HIDDEN.getProperty()));
+
+ this.setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ this.setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ }
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public Long getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(Long creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public Long getModificationTime() {
+ return modificationTime;
+ }
+
+ public void setModificationTime(Long modificationTime) {
+ this.modificationTime = modificationTime;
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, type);
+
+ addIfExists(map, GraphPropertiesDictionary.HIDDEN, hidden);
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, creationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, modificationTime);
+
+ String updatedValue = Objects.isNull(value) ? Constants.GRAPH_EMPTY_VALUE : value;
+ addIfExists(map, GraphPropertiesDictionary.VALUE, updatedValue);
+ return map;
+ }
+
+ @Override
+ public String toString() {
+ return "AttributeValueData [uniqueId=" + uniqueId + ", hidden=" + hidden + ", type=" + type + ", creationTime="
+ + creationTime + ", value=" + value + ", modificationTime=" + modificationTime + "]";
+ }
+
+ public Boolean isHidden() {
+ return hidden;
+ }
+
+ public void setHidden(Boolean hidden) {
+ this.hidden = hidden;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java
new file mode 100644
index 0000000000..2582475c5c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java
@@ -0,0 +1,182 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class CapabilityData extends GraphNode {
+ public final static String MIN_OCCURRENCES = "1"; // occurrences
+ public final static String MAX_OCCURRENCES = "UNBOUNDED";
+
+ public CapabilityData() {
+ super(NodeTypeEnum.Capability);
+
+ }
+
+ public CapabilityData(Map<String, Object> properties) {
+ this();
+
+ this.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> validSourceTypesfromJson = getGson().fromJson(
+ (String) properties.get(GraphPropertiesDictionary.VALID_SOURCE_TYPES.getProperty()), listType);
+
+ this.setValidSourceTypes(validSourceTypesfromJson);
+
+ this.setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ this.setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ this.setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+ this.setMinOccurrences((String) properties.get(GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty()));
+ this.setMaxOccurrences((String) properties.get(GraphPropertiesDictionary.MAX_OCCURRENCES.getProperty()));
+ }
+
+ private String uniqueId;
+
+ private String description;
+
+ /** Identifies the type of the capability. */
+ private String type;
+
+ private List<String> validSourceTypes;
+
+ private Long creationTime;
+
+ private Long modificationTime;
+
+ private String minOccurrences = MIN_OCCURRENCES;
+ private String maxOccurrences = MAX_OCCURRENCES;
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public List<String> getValidSourceTypes() {
+ return validSourceTypes;
+ }
+
+ public void setValidSourceTypes(List<String> validSourceTypes) {
+ this.validSourceTypes = validSourceTypes;
+ }
+
+ public Long getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(Long creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public Long getModificationTime() {
+ return modificationTime;
+ }
+
+ public void setModificationTime(Long modificationTime) {
+ this.modificationTime = modificationTime;
+ }
+
+ public String getMinOccurrences() {
+ return minOccurrences;
+ }
+
+ public void setMinOccurrences(String minOccurrences) {
+ if (minOccurrences != null) {
+ this.minOccurrences = minOccurrences;
+ }
+ }
+
+ public String getMaxOccurrences() {
+ return maxOccurrences;
+ }
+
+ public void setMaxOccurrences(String maxOccurrences) {
+ if (maxOccurrences != null) {
+ this.maxOccurrences = maxOccurrences;
+ }
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+
+ // String validSourceTypesToJson = getGson().toJson(validSourceTypes);
+
+ // addIfExists(map, GraphPropertiesDictionary.VALID_SOURCE_TYPES,
+ // validSourceTypesToJson);
+ // addIfExists(map, GraphPropertiesDictionary.VALID_SOURCE_TYPES,
+ // validSourceTypes);
+
+ addIfExists(map, GraphPropertiesDictionary.VALID_SOURCE_TYPES, validSourceTypes);
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, creationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, modificationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, description);
+ addIfExists(map, GraphPropertiesDictionary.MIN_OCCURRENCES, minOccurrences);
+ addIfExists(map, GraphPropertiesDictionary.MAX_OCCURRENCES, maxOccurrences);
+
+ return map;
+ }
+
+ @Override
+ public String toString() {
+ return "CapabilityData [uniqueId=" + uniqueId + ", description=" + description + ", type=" + type
+ + ", validSourceTypes=" + validSourceTypes + ", creationTime=" + creationTime + ", modificationTime="
+ + modificationTime + ", minOccurrences=" + minOccurrences + ", maxOccurrences=" + maxOccurrences + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java
new file mode 100644
index 0000000000..4c9bf6767e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java
@@ -0,0 +1,128 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class CapabilityInstData extends GraphNode {
+
+ public CapabilityInstData() {
+ super(NodeTypeEnum.CapabilityInst);
+ }
+
+ public CapabilityInstData(Map<String, Object> properties) {
+ this();
+
+ this.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> propertiesfromJson = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.PROPERTIES.getProperty()), listType);
+
+ this.setProperties(propertiesfromJson);
+
+ // this.setProperties((ArrayList<String>) properties
+ // .get(GraphPropertiesDictionary.PROPERTIES.getProperty()));
+
+ this.setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ this.setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+ }
+
+ private String uniqueId;
+
+ private List<String> properties;
+
+ private Long creationTime;
+
+ private Long modificationTime;
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public Long getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(Long creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public Long getModificationTime() {
+ return modificationTime;
+ }
+
+ public void setModificationTime(Long modificationTime) {
+ this.modificationTime = modificationTime;
+ }
+
+ public List<String> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(List<String> properties) {
+ this.properties = properties;
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+
+ // String propertiesToJson = getGson().toJson(properties);
+
+ // addIfExists(map, GraphPropertiesDictionary.PROPERTIES,
+ // propertiesToJson);
+
+ addIfExists(map, GraphPropertiesDictionary.PROPERTIES, properties);
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, creationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, modificationTime);
+
+ return map;
+ }
+
+ @Override
+ public String toString() {
+ return "CapabilityInstData [uniqueId=" + uniqueId + ", properties=" + properties + ", creationTime="
+ + creationTime + ", modificationTime=" + modificationTime + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityTypeData.java
new file mode 100644
index 0000000000..81e8ce9174
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityTypeData.java
@@ -0,0 +1,131 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityTypeDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class CapabilityTypeData extends GraphNode {
+
+ CapabilityTypeDataDefinition capabilityTypeDataDefinition;
+
+ // private List<String> constraints;
+
+ public CapabilityTypeData() {
+ super(NodeTypeEnum.CapabilityType);
+ capabilityTypeDataDefinition = new CapabilityTypeDataDefinition();
+ }
+
+ public CapabilityTypeData(CapabilityTypeDataDefinition capabilityTypeDataDefinition) {
+ super(NodeTypeEnum.CapabilityType);
+ this.capabilityTypeDataDefinition = capabilityTypeDataDefinition;
+ // this.constraints = constraints;
+ }
+
+ public CapabilityTypeData(Map<String, Object> properties) {
+
+ this();
+
+ capabilityTypeDataDefinition
+ .setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ capabilityTypeDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+
+ capabilityTypeDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+
+ Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> validSourceTypesfromJson = getGson().fromJson(
+ (String) properties.get(GraphPropertiesDictionary.VALID_SOURCE_TYPES.getProperty()), listType);
+
+ capabilityTypeDataDefinition.setValidSourceTypes(validSourceTypesfromJson);
+
+ // capabilityTypeDataDefinition.setValidSourceTypes((List<String>)
+ // properties.get(GraphPropertiesDictionary.VALID_SOURCE_TYPES
+ // .getProperty()));
+
+ capabilityTypeDataDefinition
+ .setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ capabilityTypeDataDefinition
+ .setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ // capabilityTypeDataDefinition.setVersion(version);
+
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, capabilityTypeDataDefinition.getUniqueId());
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, capabilityTypeDataDefinition.getType());
+
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, capabilityTypeDataDefinition.getDescription());
+
+ // String validSourceTypesToJson =
+ // getGson().toJson(capabilityTypeDataDefinition.getValidSourceTypes());
+
+ // addIfExists(map, GraphPropertiesDictionary.VALID_SOURCE_TYPES,
+ // validSourceTypesToJson);
+
+ addIfExists(map, GraphPropertiesDictionary.VALID_SOURCE_TYPES,
+ capabilityTypeDataDefinition.getValidSourceTypes());
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, capabilityTypeDataDefinition.getCreationTime());
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE,
+ capabilityTypeDataDefinition.getModificationTime());
+
+ return map;
+ }
+
+ public CapabilityTypeDataDefinition getCapabilityTypeDataDefinition() {
+ return capabilityTypeDataDefinition;
+ }
+
+ public void setCapabilityTypeDataDefinition(CapabilityTypeDataDefinition capabilityTypeDataDefinition) {
+ this.capabilityTypeDataDefinition = capabilityTypeDataDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "CapabilityTypeData [capabilityTypeDataDefinition=" + capabilityTypeDataDefinition + "]";
+ }
+
+ @Override
+ public String getUniqueId() {
+ return this.capabilityTypeDataDefinition.getUniqueId();
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java
new file mode 100644
index 0000000000..4cfde8b0fa
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java
@@ -0,0 +1,114 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public abstract class CategoryData extends GraphNode {
+
+ private String name;
+ private String normalizedName;
+ private String uniqueId;
+
+ protected abstract void createUniqueId();
+
+ protected CategoryData(NodeTypeEnum label) {
+ super(label);
+ }
+
+ protected CategoryData(String name, String normalizedName, NodeTypeEnum label) {
+ super(label);
+ this.name = name;
+ this.normalizedName = normalizedName;
+ }
+
+ protected CategoryData(Map<String, Object> properties, NodeTypeEnum label) {
+ super(label);
+ setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+ setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ setNormalizedName((String) properties.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()));
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+ addIfExists(map, GraphPropertiesDictionary.NAME, name);
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+ addIfExists(map, GraphPropertiesDictionary.NORMALIZED_NAME, normalizedName);
+ return map;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getNormalizedName() {
+ return normalizedName;
+ }
+
+ public void setNormalizedName(String normalizedName) {
+ this.normalizedName = normalizedName;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ @Override
+ public String toString() {
+ return "CategoryData [name=" + name + ", normalizedName=" + normalizedName + "uniqueId=" + uniqueId + "]";
+ }
+
+ /*
+ * @Override public int hashCode() { final int prime = 31; int result = 1;
+ * result = prime * result + ((name == null) ? 0 : name.hashCode()); result
+ * = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode()); return
+ * result; }
+ *
+ * @Override public boolean equals(Object obj) { if (this == obj) return
+ * true; if (obj == null) return false; if (getClass() != obj.getClass())
+ * return false; CategoryData other = (CategoryData) obj; if (name == null)
+ * { if (other.name != null) return false; } else if
+ * (!name.equals(other.name)) return false; if (uniqueId == null) { if
+ * (other.uniqueId != null) return false; } else if
+ * (!uniqueId.equals(other.uniqueId)) return false; return true; }
+ */
+
+ @Override
+ public String getUniqueIdKey() {
+ return GraphPropertiesDictionary.UNIQUE_ID.getProperty();
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return uniqueId;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentCacheData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentCacheData.java
new file mode 100644
index 0000000000..727740002c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentCacheData.java
@@ -0,0 +1,153 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.nio.ByteBuffer;
+import java.util.Date;
+
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = "sdccomponent", name = "componentcache")
+public class ComponentCacheData {
+ public final static String RRESOURCE_ID_FIELD = "resourceId";
+
+ public final static String SERVICE_NAME_FIELD = "serviceName";
+ public final static String SERVICE_VERSION_FIELD = "serviceVersion";
+ public final static String ARTIFACT_NAME_FIELD = "artifactName";
+
+ public static String delim = ":";
+
+ @PartitionKey
+ @Column(name = "id")
+ private String id;
+
+ @Column
+ private ByteBuffer data;
+
+ @Column(name = "modification_time")
+ private Date modificationTime;
+
+ @Column
+ private String type;
+
+ @Column(name = "is_dirty")
+ private boolean isDirty;
+
+ @Column(name = "is_zipped")
+ private boolean isZipped;
+
+ public ComponentCacheData() {
+
+ }
+
+ public ComponentCacheData(String id, byte[] data, Date modificationTime, String type, boolean isDirty,
+ boolean isZipped) {
+ super();
+ this.id = id;
+ if (data != null) {
+ this.data = ByteBuffer.wrap(data.clone());
+ }
+ this.modificationTime = modificationTime;
+ this.type = type;
+ this.isDirty = isDirty;
+ this.isZipped = isZipped;
+ }
+
+ public ComponentCacheData(String id) {
+
+ this.id = id;
+ }
+
+ public ComponentCacheData(String artifactId, byte[] data) {
+ super();
+ this.id = artifactId;
+ if (data != null) {
+ this.data = ByteBuffer.wrap(data.clone());
+ // this.data = data.clone();
+ }
+ }
+
+ public byte[] getDataAsArray() {
+ if (data != null) {
+ return data.array();
+ }
+ return null;
+ }
+
+ public void setDataAsArray(byte[] data) {
+ if (data != null) {
+ this.data = ByteBuffer.wrap(data.clone());
+ }
+ }
+
+ public ByteBuffer getData() {
+ return data;
+ }
+
+ public void setData(ByteBuffer data) {
+ if (data != null) {
+ this.data = data.duplicate();
+ }
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public Date getModificationTime() {
+ return modificationTime;
+ }
+
+ public void setModificationTime(Date modificationTime) {
+ this.modificationTime = modificationTime;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public boolean getIsDirty() {
+ return isDirty;
+ }
+
+ public void setIsDirty(boolean isDirty) {
+ this.isDirty = isDirty;
+ }
+
+ public boolean getIsZipped() {
+ return isZipped;
+ }
+
+ public void setIsZipped(boolean isZipped) {
+ this.isZipped = isZipped;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java
new file mode 100644
index 0000000000..c61b99a805
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java
@@ -0,0 +1,114 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+
+public class ComponentInstanceData extends GraphNode {
+
+ ComponentInstanceDataDefinition componentInstDataDefinition;
+
+ public ComponentInstanceData() {
+ super(NodeTypeEnum.ResourceInstance);
+ this.componentInstDataDefinition = new ComponentInstanceDataDefinition();
+ }
+
+ public ComponentInstanceData(ComponentInstanceDataDefinition componentInstDataDefinition) {
+ super(NodeTypeEnum.ResourceInstance);
+ this.componentInstDataDefinition = componentInstDataDefinition;
+ }
+
+ public ComponentInstanceData(Map<String, Object> properties) {
+
+ this();
+
+ componentInstDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ componentInstDataDefinition.setComponentUid((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+ componentInstDataDefinition.setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+ componentInstDataDefinition.setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+ componentInstDataDefinition.setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+ componentInstDataDefinition.setPosX((String) properties.get(GraphPropertiesDictionary.POSITION_X.getProperty()));
+ componentInstDataDefinition.setPosY((String) properties.get(GraphPropertiesDictionary.POSITION_Y.getProperty()));
+ componentInstDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+ componentInstDataDefinition.setPropertyValueCounter((Integer) properties.get(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty()));
+ componentInstDataDefinition.setAttributeValueCounter((Integer) properties.get(GraphPropertiesDictionary.ATTRIBUTE_COUNTER.getProperty()));
+ componentInstDataDefinition.setNormalizedName((String) properties.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()));
+ componentInstDataDefinition.setOriginType(OriginTypeEnum.findByValue((String) properties.get(GraphPropertiesDictionary.ORIGIN_TYPE.getProperty())));
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, componentInstDataDefinition.getComponentUid());
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, componentInstDataDefinition.getCreationTime());
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, componentInstDataDefinition.getModificationTime());
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, componentInstDataDefinition.getDescription());
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, componentInstDataDefinition.getUniqueId());
+ addIfExists(map, GraphPropertiesDictionary.POSITION_X, componentInstDataDefinition.getPosX());
+ addIfExists(map, GraphPropertiesDictionary.POSITION_Y, componentInstDataDefinition.getPosY());
+ addIfExists(map, GraphPropertiesDictionary.NAME, componentInstDataDefinition.getName());
+ addIfExists(map, GraphPropertiesDictionary.PROPERTY_COUNTER, componentInstDataDefinition.getPropertyValueCounter());
+ addIfExists(map, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, componentInstDataDefinition.getAttributeValueCounter());
+ addIfExists(map, GraphPropertiesDictionary.NORMALIZED_NAME, componentInstDataDefinition.getNormalizedName());
+ if (componentInstDataDefinition.getOriginType() != null) {
+ addIfExists(map, GraphPropertiesDictionary.ORIGIN_TYPE, componentInstDataDefinition.getOriginType().getValue());
+ }
+
+ return map;
+ }
+
+ @Override
+ public String getUniqueId() {
+ return componentInstDataDefinition.getUniqueId();
+ }
+
+ public String getName() {
+ return componentInstDataDefinition.getName();
+ }
+
+ @Override
+ public String getUniqueIdKey() {
+ return GraphPropertiesDictionary.UNIQUE_ID.getProperty();
+ }
+
+ public ComponentInstanceDataDefinition getComponentInstDataDefinition() {
+ return componentInstDataDefinition;
+ }
+
+ public void setComponentInstDataDefinition(ComponentInstanceDataDefinition componentInstDataDefinition) {
+ this.componentInstDataDefinition = componentInstDataDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "ComponentInstanceData [componentInstDataDefinition=" + componentInstDataDefinition + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java
new file mode 100644
index 0000000000..e39dfe226f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java
@@ -0,0 +1,147 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public abstract class ComponentMetadataData extends GraphNode {
+
+ protected ComponentMetadataDataDefinition metadataDataDefinition;
+ protected Integer componentInstanceCounter;
+
+ public ComponentMetadataData(NodeTypeEnum label, ComponentMetadataDataDefinition metadataDataDefinition) {
+ super(label);
+ this.metadataDataDefinition = metadataDataDefinition;
+ this.componentInstanceCounter = 0;
+ }
+
+ public ComponentMetadataData(NodeTypeEnum label, ComponentMetadataDataDefinition metadataDataDefinition,
+ Map<String, Object> properties) {
+ this(label, metadataDataDefinition);
+ metadataDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ metadataDataDefinition
+ .setCreationDate((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+ metadataDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+ metadataDataDefinition.setIcon((String) properties.get(GraphPropertiesDictionary.ICON.getProperty()));
+ metadataDataDefinition.setHighestVersion(
+ (Boolean) properties.get(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()));
+ metadataDataDefinition
+ .setLastUpdateDate((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+ metadataDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+ metadataDataDefinition.setState((String) properties.get(GraphPropertiesDictionary.STATE.getProperty()));
+ Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> tagsFromJson = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.TAGS.getProperty()), listType);
+ metadataDataDefinition.setTags(tagsFromJson);
+ metadataDataDefinition.setVersion((String) properties.get(GraphPropertiesDictionary.VERSION.getProperty()));
+ metadataDataDefinition
+ .setContactId((String) properties.get(GraphPropertiesDictionary.CONTACT_ID.getProperty()));
+ metadataDataDefinition.setUUID((String) properties.get(GraphPropertiesDictionary.UUID.getProperty()));
+ metadataDataDefinition
+ .setNormalizedName((String) properties.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()));
+ metadataDataDefinition
+ .setSystemName((String) properties.get(GraphPropertiesDictionary.SYSTEM_NAME.getProperty()));
+ metadataDataDefinition
+ .setIsDeleted((Boolean) properties.get(GraphPropertiesDictionary.IS_DELETED.getProperty()));
+ metadataDataDefinition.setProjectCode((String) properties.get(GraphPropertiesDictionary.PROJECT_CODE.getProperty()));
+ metadataDataDefinition.setCsarUUID((String) properties.get(GraphPropertiesDictionary.CSAR_UUID.getProperty()));
+ metadataDataDefinition
+ .setCsarVersion((String) properties.get(GraphPropertiesDictionary.CSAR_VERSION.getProperty()));
+ metadataDataDefinition.setImportedToscaChecksum(
+ (String) properties.get(GraphPropertiesDictionary.IMPORTED_TOSCA_CHECKSUM.getProperty()));
+ metadataDataDefinition
+ .setInvariantUUID((String) properties.get(GraphPropertiesDictionary.INVARIANT_UUID.getProperty()));
+ componentInstanceCounter = (Integer) properties.get(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty());
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, metadataDataDefinition.getUniqueId());
+ addIfExists(map, GraphPropertiesDictionary.VERSION, metadataDataDefinition.getVersion());
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, metadataDataDefinition.getCreationDate());
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, metadataDataDefinition.getDescription());
+ addIfExists(map, GraphPropertiesDictionary.ICON, metadataDataDefinition.getIcon());
+ addIfExists(map, GraphPropertiesDictionary.IS_HIGHEST_VERSION, metadataDataDefinition.isHighestVersion());
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, metadataDataDefinition.getLastUpdateDate());
+ addIfExists(map, GraphPropertiesDictionary.STATE, metadataDataDefinition.getState());
+ addIfExists(map, GraphPropertiesDictionary.TAGS, metadataDataDefinition.getTags());
+ addIfExists(map, GraphPropertiesDictionary.CONTACT_ID, metadataDataDefinition.getContactId());
+ addIfExists(map, GraphPropertiesDictionary.NAME, metadataDataDefinition.getName());
+ addIfExists(map, GraphPropertiesDictionary.UUID, metadataDataDefinition.getUUID());
+ addIfExists(map, GraphPropertiesDictionary.NORMALIZED_NAME, metadataDataDefinition.getNormalizedName());
+ addIfExists(map, GraphPropertiesDictionary.SYSTEM_NAME, metadataDataDefinition.getSystemName());
+ addIfExists(map, GraphPropertiesDictionary.IS_DELETED, metadataDataDefinition.isDeleted());
+ addIfExists(map, GraphPropertiesDictionary.INSTANCE_COUNTER, componentInstanceCounter);
+ addIfExists(map, GraphPropertiesDictionary.PROJECT_CODE, metadataDataDefinition.getProjectCode());
+ addIfExists(map, GraphPropertiesDictionary.CSAR_UUID, metadataDataDefinition.getCsarUUID());
+ addIfExists(map, GraphPropertiesDictionary.CSAR_VERSION, metadataDataDefinition.getCsarVersion());
+ addIfExists(map, GraphPropertiesDictionary.IMPORTED_TOSCA_CHECKSUM,
+ metadataDataDefinition.getImportedToscaChecksum());
+ addIfExists(map, GraphPropertiesDictionary.INVARIANT_UUID, metadataDataDefinition.getInvariantUUID());
+ return map;
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return metadataDataDefinition.getUniqueId();
+ }
+
+ public ComponentMetadataDataDefinition getMetadataDataDefinition() {
+ return metadataDataDefinition;
+ }
+
+ public void setMetadataDataDefinition(ComponentMetadataDataDefinition metadataDataDefinition) {
+ this.metadataDataDefinition = metadataDataDefinition;
+ }
+
+ public Integer getComponentInstanceCounter() {
+ return componentInstanceCounter;
+ }
+
+ public void setComponentInstanceCounter(Integer componentInstanceCounter) {
+ this.componentInstanceCounter = componentInstanceCounter;
+ }
+
+ public Integer increaseAndGetComponentInstanceCounter() {
+ return ++componentInstanceCounter;
+ }
+
+ @Override
+ public String toString() {
+ return "ComponentMetadataData [metadataDataDefinition=" + metadataDataDefinition + ", componentInstanceCounter="
+ + componentInstanceCounter + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java
new file mode 100644
index 0000000000..1016930e2a
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java
@@ -0,0 +1,92 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class ConsumerData extends GraphNode {
+
+ private ConsumerDataDefinition consumerDataDefinition;
+
+ public ConsumerData() {
+ super(NodeTypeEnum.ConsumerCredentials);
+ consumerDataDefinition = new ConsumerDataDefinition();
+ }
+
+ public ConsumerData(ConsumerDataDefinition consumerDataDefinition) {
+ super(NodeTypeEnum.ConsumerCredentials);
+ this.consumerDataDefinition = consumerDataDefinition;
+
+ }
+
+ public ConsumerData(Map<String, Object> properties) {
+ super(NodeTypeEnum.ConsumerCredentials);
+ consumerDataDefinition = new ConsumerDataDefinition();
+ consumerDataDefinition.setConsumerDetailsLastupdatedtime((Long) properties.get(GraphPropertiesDictionary.CONSUMER_DETAILS_LAST_UPDATED_TIME.getProperty()));
+ consumerDataDefinition.setConsumerLastAuthenticationTime((Long) properties.get(GraphPropertiesDictionary.CONSUMER_LAST_AUTHENTICATION_TIME.getProperty()));
+ consumerDataDefinition.setConsumerName((String) properties.get(GraphPropertiesDictionary.CONSUMER_NAME.getProperty()));
+ consumerDataDefinition.setConsumerPassword((String) properties.get(GraphPropertiesDictionary.CONSUMER_PASSWORD.getProperty()));
+ consumerDataDefinition.setConsumerSalt((String) properties.get(GraphPropertiesDictionary.CONSUMER_SALT.getProperty()));
+ consumerDataDefinition.setLastModfierAtuid((String) properties.get(GraphPropertiesDictionary.LAST_MODIFIER_USER_ID.getProperty()));
+ }
+
+ @Override
+ public String getUniqueIdKey() {
+ return GraphPropertiesDictionary.CONSUMER_NAME.getProperty();
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return consumerDataDefinition.getConsumerName();
+ }
+
+ public ConsumerDataDefinition getConsumerDataDefinition() {
+ return consumerDataDefinition;
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+ addIfExists(map, GraphPropertiesDictionary.CONSUMER_NAME, this.consumerDataDefinition.getConsumerName());
+ addIfExists(map, GraphPropertiesDictionary.CONSUMER_PASSWORD,
+ this.consumerDataDefinition.getConsumerPassword());
+ addIfExists(map, GraphPropertiesDictionary.CONSUMER_SALT, this.consumerDataDefinition.getConsumerSalt());
+ addIfExists(map, GraphPropertiesDictionary.CONSUMER_LAST_AUTHENTICATION_TIME,
+ this.consumerDataDefinition.getConsumerLastAuthenticationTime());
+ addIfExists(map, GraphPropertiesDictionary.CONSUMER_DETAILS_LAST_UPDATED_TIME,
+ this.consumerDataDefinition.getConsumerDetailsLastupdatedtime());
+ addIfExists(map, GraphPropertiesDictionary.LAST_MODIFIER_USER_ID,
+ this.consumerDataDefinition.getLastModfierAtuid());
+
+ return map;
+ }
+
+ @Override
+ public String toString() {
+ return "ConsumerData [consumerDataDefinition=" + consumerDataDefinition + "]";
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/DataTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/DataTypeData.java
new file mode 100644
index 0000000000..2f745243c6
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/DataTypeData.java
@@ -0,0 +1,106 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class DataTypeData extends GraphNode {
+
+ DataTypeDataDefinition dataTypeDataDefinition;
+
+ public DataTypeData() {
+ super(NodeTypeEnum.DataType);
+ dataTypeDataDefinition = new DataTypeDataDefinition();
+ }
+
+ public DataTypeData(DataTypeDataDefinition dataTypeDataDefinition) {
+ super(NodeTypeEnum.DataType);
+ this.dataTypeDataDefinition = dataTypeDataDefinition;
+ // this.constraints = constraints;
+ }
+
+ public DataTypeData(Map<String, Object> properties) {
+
+ this();
+
+ dataTypeDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ dataTypeDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+
+ dataTypeDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+
+ dataTypeDataDefinition
+ .setDerivedFromName((String) properties.get(GraphPropertiesDictionary.DERIVED_FROM.getProperty()));
+
+ dataTypeDataDefinition
+ .setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ dataTypeDataDefinition
+ .setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, dataTypeDataDefinition.getUniqueId());
+
+ addIfExists(map, GraphPropertiesDictionary.NAME, dataTypeDataDefinition.getName());
+
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, dataTypeDataDefinition.getDescription());
+
+ addIfExists(map, GraphPropertiesDictionary.DERIVED_FROM, dataTypeDataDefinition.getDerivedFromName());
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, dataTypeDataDefinition.getCreationTime());
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, dataTypeDataDefinition.getModificationTime());
+
+ return map;
+ }
+
+ public DataTypeDataDefinition getDataTypeDataDefinition() {
+ return dataTypeDataDefinition;
+ }
+
+ public void setDataTypeDataDefinition(DataTypeDataDefinition dataTypeDataDefinition) {
+ this.dataTypeDataDefinition = dataTypeDataDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "DataTypeData [dataTypeDataDefinition=" + dataTypeDataDefinition + "]";
+ }
+
+ @Override
+ public String getUniqueId() {
+ return this.dataTypeDataDefinition.getUniqueId();
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java
new file mode 100644
index 0000000000..56101d031f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java
@@ -0,0 +1,106 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.nio.ByteBuffer;
+
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = "sdcArtifact", name = "resources")
+public class ESArtifactData {
+ public final static String RRESOURCE_ID_FIELD = "resourceId";
+
+ public final static String SERVICE_NAME_FIELD = "serviceName";
+ public final static String SERVICE_VERSION_FIELD = "serviceVersion";
+ public final static String ARTIFACT_NAME_FIELD = "artifactName";
+
+ public static String delim = ":";
+
+ @PartitionKey
+ @Column(name = "id")
+ private String id;
+
+ /*
+ * Base64 encoded Artifact file data
+ */
+
+ @Column
+ private ByteBuffer data;
+
+ // private byte[] data;
+
+ public ESArtifactData() {
+
+ }
+
+ public ESArtifactData(String id) {
+
+ this.id = id;
+ }
+
+ public ESArtifactData(String artifactId, byte[] data) {
+ super();
+ this.id = artifactId;
+ if (data != null) {
+ this.data = ByteBuffer.wrap(data.clone());
+ // this.data = data.clone();
+ }
+
+ }
+
+ public byte[] getDataAsArray() {
+ // return data;
+ if (data != null) {
+ return data.array();
+ }
+ return null;
+ }
+
+ public void setDataAsArray(byte[] data) {
+ if (data != null) {
+ // this.data = data.clone();
+ this.data = ByteBuffer.wrap(data.clone());
+ }
+ }
+
+ public ByteBuffer getData() {
+ // return data;
+ return data;
+ }
+
+ public void setData(ByteBuffer data) {
+ if (data != null) {
+ // this.data = data.clone();
+ this.data = data.duplicate();
+ }
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/EntryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/EntryData.java
new file mode 100644
index 0000000000..a3229bf88a
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/EntryData.java
@@ -0,0 +1,52 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.Map;
+
+public class EntryData<K, V> implements Map.Entry<K, V> {
+
+ private final K key;
+ private V value;
+
+ public EntryData(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+
+ @Override
+ public K getKey() {
+ return key;
+ }
+
+ @Override
+ public V getValue() {
+ return value;
+ }
+
+ @Override
+ public V setValue(V value) {
+ V old = this.value;
+ this.value = value;
+ return old;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java
new file mode 100644
index 0000000000..200521c054
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java
@@ -0,0 +1,79 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class GraphNodeLock extends GraphNode {
+
+ private String uniqueId;
+ private Long time;
+
+ public GraphNodeLock() {
+ super(NodeTypeEnum.LockNode);
+ time = System.currentTimeMillis();
+ }
+
+ public GraphNodeLock(String uniqueId) {
+ this();
+ this.uniqueId = uniqueId;
+ }
+
+ public GraphNodeLock(Map<String, Object> properties) {
+ super(NodeTypeEnum.LockNode);
+
+ setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ setTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return uniqueId;
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, time);
+ return map;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public Long getTime() {
+ return time;
+ }
+
+ public void setTime(Long time) {
+ this.time = time;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java
new file mode 100644
index 0000000000..e354e95b27
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java
@@ -0,0 +1,97 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class GroupData extends GraphNode {
+
+ GroupDataDefinition groupDataDefinition;
+
+ public GroupData() {
+ super(NodeTypeEnum.Group);
+ groupDataDefinition = new GroupDataDefinition();
+ }
+
+ public GroupData(GroupDataDefinition groupDataDefinition) {
+ super(NodeTypeEnum.Group);
+ this.groupDataDefinition = groupDataDefinition;
+ }
+
+ public GroupData(Map<String, Object> properties) {
+
+ super(NodeTypeEnum.Group);
+
+ groupDataDefinition = new GroupDataDefinition();
+
+ groupDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+ groupDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ groupDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+ groupDataDefinition.setVersion((String) properties.get(GraphPropertiesDictionary.VERSION.getProperty()));
+ groupDataDefinition
+ .setInvariantUUID((String) properties.get(GraphPropertiesDictionary.INVARIANT_UUID.getProperty()));
+ groupDataDefinition.setGroupUUID((String) properties.get(GraphPropertiesDictionary.GROUP_UUID.getProperty()));
+ groupDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+ groupDataDefinition.setPropertyValueCounter(
+ (Integer) properties.get(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty()));
+
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return groupDataDefinition.getUniqueId();
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+ addIfExists(map, GraphPropertiesDictionary.NAME, groupDataDefinition.getName());
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, groupDataDefinition.getUniqueId());
+ addIfExists(map, GraphPropertiesDictionary.TYPE, groupDataDefinition.getType());
+ addIfExists(map, GraphPropertiesDictionary.VERSION, groupDataDefinition.getVersion());
+ addIfExists(map, GraphPropertiesDictionary.INVARIANT_UUID, groupDataDefinition.getInvariantUUID());
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, groupDataDefinition.getDescription());
+ addIfExists(map, GraphPropertiesDictionary.PROPERTY_COUNTER, groupDataDefinition.getPropertyValueCounter());
+ addIfExists(map, GraphPropertiesDictionary.GROUP_UUID, groupDataDefinition.getGroupUUID());
+
+ return map;
+ }
+
+ public GroupDataDefinition getGroupDataDefinition() {
+ return groupDataDefinition;
+ }
+
+ public void setGroupDataDefinition(GroupDataDefinition groupDataDefinition) {
+ this.groupDataDefinition = groupDataDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "GroupData [ " + groupDataDefinition.toString() + "]";
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupTypeData.java
new file mode 100644
index 0000000000..87f4fcf283
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupTypeData.java
@@ -0,0 +1,130 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class GroupTypeData extends GraphNode {
+
+ private static Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ private static Type mapType = new TypeToken<HashMap<String, String>>() {
+ }.getType();
+
+ GroupTypeDataDefinition groupTypeDataDefinition;
+
+ public GroupTypeData() {
+ super(NodeTypeEnum.GroupType);
+ groupTypeDataDefinition = new GroupTypeDataDefinition();
+ }
+
+ public GroupTypeData(GroupTypeDataDefinition groupTypeDataDefinition) {
+ super(NodeTypeEnum.GroupType);
+ this.groupTypeDataDefinition = groupTypeDataDefinition;
+ }
+
+ public GroupTypeData(Map<String, Object> properties) {
+
+ this();
+
+ groupTypeDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ groupTypeDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+
+ groupTypeDataDefinition.setVersion((String) properties.get(GraphPropertiesDictionary.VERSION.getProperty()));
+
+ groupTypeDataDefinition.setHighestVersion(
+ (boolean) properties.get(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()));
+
+ groupTypeDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+
+ List<String> members = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.MEMBERS.getProperty()), listType);
+ groupTypeDataDefinition.setMembers(members);
+
+ HashMap<String, String> metatdata = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.METADATA.getProperty()), mapType);
+ groupTypeDataDefinition.setMetadata(metatdata);
+
+ groupTypeDataDefinition
+ .setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ groupTypeDataDefinition
+ .setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, groupTypeDataDefinition.getUniqueId());
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, groupTypeDataDefinition.getType());
+
+ addIfExists(map, GraphPropertiesDictionary.VERSION, groupTypeDataDefinition.getVersion());
+
+ addIfExists(map, GraphPropertiesDictionary.IS_HIGHEST_VERSION, groupTypeDataDefinition.isHighestVersion());
+
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, groupTypeDataDefinition.getDescription());
+
+ addIfExists(map, GraphPropertiesDictionary.METADATA, groupTypeDataDefinition.getMetadata());
+
+ addIfExists(map, GraphPropertiesDictionary.MEMBERS, groupTypeDataDefinition.getMembers());
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, groupTypeDataDefinition.getCreationTime());
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, groupTypeDataDefinition.getModificationTime());
+
+ return map;
+ }
+
+ public GroupTypeDataDefinition getGroupTypeDataDefinition() {
+ return groupTypeDataDefinition;
+ }
+
+ public void setGroupTypeDataDefinition(GroupTypeDataDefinition groupTypeDataDefinition) {
+ this.groupTypeDataDefinition = groupTypeDataDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "GroupTypeData [groupTypeDataDefinition=" + groupTypeDataDefinition + "]";
+ }
+
+ @Override
+ public String getUniqueId() {
+ return this.groupTypeDataDefinition.getUniqueId();
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java
new file mode 100644
index 0000000000..7115a45bf3
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java
@@ -0,0 +1,172 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.math.BigDecimal;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.Constants;
+import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class HeatParameterData extends GraphNode {
+
+ private HeatParameterDataDefinition heatDataDefinition;
+
+ public HeatParameterData() {
+ super(NodeTypeEnum.HeatParameter);
+ heatDataDefinition = new HeatParameterDataDefinition();
+ }
+
+ public HeatParameterData(HeatParameterDataDefinition heatDataDef) {
+ super(NodeTypeEnum.HeatParameter);
+ this.heatDataDefinition = heatDataDef;
+ }
+
+ public HeatParameterData(Map<String, Object> properties) {
+ this();
+
+ heatDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ heatDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+ String type = (String) properties.get(GraphPropertiesDictionary.TYPE.getProperty());
+ heatDataDefinition.setType(type);
+
+ String description = (String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty());
+ if (Constants.GRAPH_EMPTY_VALUE.equals(description)) {
+ heatDataDefinition.setDescription(null);
+ } else {
+ heatDataDefinition.setDescription(description);
+ }
+
+ String defaultValue = (String) properties.get(GraphPropertiesDictionary.DEFAULT_VALUE.getProperty());
+ if (Constants.GRAPH_EMPTY_VALUE.equals(defaultValue)) {
+ heatDataDefinition.setDefaultValue(null);
+ } else {
+ heatDataDefinition.setDefaultValue(getValue(type, defaultValue));
+ }
+
+ String value = (String) properties.get(GraphPropertiesDictionary.VALUE.getProperty());
+ if (Constants.GRAPH_EMPTY_VALUE.equals(value)) {
+ heatDataDefinition.setCurrentValue(null);
+ } else {
+ heatDataDefinition.setCurrentValue(getValue(type, value));
+ }
+
+ }
+
+ private String getValue(String type, String value) {
+ if (Constants.GRAPH_EMPTY_VALUE.equals(value)) {
+ return value;
+ }
+ if ("number".equals(type)) {
+ return new BigDecimal(value).toPlainString();
+ }
+ return value;
+ }
+
+ public HeatParameterDataDefinition getHeatDataDefinition() {
+ return heatDataDefinition;
+ }
+
+ public void setHeatDataDefinition(HeatParameterDataDefinition heatDataDefinition) {
+ this.heatDataDefinition = heatDataDefinition;
+ }
+
+ public String getName() {
+ return heatDataDefinition.getName();
+ }
+
+ public void setName(String name) {
+ heatDataDefinition.setName(name);
+ }
+
+ public String getType() {
+ return heatDataDefinition.getType();
+ }
+
+ public void setType(String type) {
+ heatDataDefinition.setType(type);
+ }
+
+ public String getDescription() {
+ return heatDataDefinition.getDescription();
+ }
+
+ public void setDescription(String description) {
+ heatDataDefinition.setDescription(description);
+ }
+
+ public String getCurrentValue() {
+ return heatDataDefinition.getCurrentValue();
+ }
+
+ public void setCurrentValue(String currentValue) {
+ heatDataDefinition.setCurrentValue(currentValue);
+ }
+
+ public String getDefaultValue() {
+ return heatDataDefinition.getDefaultValue();
+ }
+
+ public void setDefaultValue(String defaultValue) {
+ heatDataDefinition.setDefaultValue(defaultValue);
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return heatDataDefinition.getUniqueId();
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, getUniqueId());
+
+ addIfExists(map, GraphPropertiesDictionary.NAME, getName());
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, getType());
+
+ String description = getDescription();
+ if (description == null) {
+ description = Constants.GRAPH_EMPTY_VALUE;
+ }
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, description);
+
+ String defaultVal = getDefaultValue();
+ if (defaultVal == null) {
+ defaultVal = Constants.GRAPH_EMPTY_VALUE;
+ }
+ addIfExists(map, GraphPropertiesDictionary.DEFAULT_VALUE, getValue(getType(), defaultVal));
+
+ String currentVal = getCurrentValue();
+ if (currentVal == null) {
+ currentVal = Constants.GRAPH_EMPTY_VALUE;
+ }
+
+ addIfExists(map, GraphPropertiesDictionary.VALUE, getValue(getType(), currentVal));
+ return map;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java
new file mode 100644
index 0000000000..ecabe22b80
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java
@@ -0,0 +1,91 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.Constants;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class HeatParameterValueData extends GraphNode {
+
+ public HeatParameterValueData() {
+ super(NodeTypeEnum.HeatParameterValue);
+ }
+
+ public HeatParameterValueData(Map<String, Object> properties) {
+ this();
+
+ this.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ String value = (String) properties.get(GraphPropertiesDictionary.VALUE.getProperty());
+ if (Constants.GRAPH_EMPTY_VALUE.equals(value)) {
+ this.setValue(null);
+ } else {
+ this.setValue(value);
+ }
+
+ }
+
+ private String uniqueId;
+
+ private String value;
+
+ @Override
+ public Object getUniqueId() {
+ return uniqueId;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+
+ String updatedValue = value;
+ if (updatedValue == null) {
+ updatedValue = Constants.GRAPH_EMPTY_VALUE;
+ }
+ addIfExists(map, GraphPropertiesDictionary.VALUE, updatedValue);
+
+ return map;
+ }
+
+ @Override
+ public String toString() {
+ return "HeatParameterValueData [uniqueId=" + uniqueId + ", value=" + value + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java
new file mode 100644
index 0000000000..1ed3ef1135
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java
@@ -0,0 +1,145 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.Constants;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class InputValueData extends GraphNode {
+ private String uniqueId;
+
+ private String value;
+
+ private String type;
+
+ private Boolean hidden;
+
+ private Long creationTime;
+
+ private Long modificationTime;
+
+ public InputValueData() {
+ super(NodeTypeEnum.InputValue);
+ }
+
+ public InputValueData(Map<String, Object> properties) {
+ this();
+
+ this.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+
+ String updatedValue = (String) properties.get(GraphPropertiesDictionary.VALUE.getProperty());
+ if (Constants.GRAPH_EMPTY_VALUE.equals(updatedValue)) {
+ this.setValue(null);
+ } else {
+ this.setValue(updatedValue);
+ }
+
+ this.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ this.setHidden((Boolean) properties.get(GraphPropertiesDictionary.HIDDEN.getProperty()));
+
+ this.setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ this.setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ }
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public Long getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(Long creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public Long getModificationTime() {
+ return modificationTime;
+ }
+
+ public void setModificationTime(Long modificationTime) {
+ this.modificationTime = modificationTime;
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, type);
+
+ addIfExists(map, GraphPropertiesDictionary.HIDDEN, hidden);
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, creationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, modificationTime);
+
+ String updatedValue = Objects.isNull(value) ? Constants.GRAPH_EMPTY_VALUE : value;
+ addIfExists(map, GraphPropertiesDictionary.VALUE, updatedValue);
+ return map;
+ }
+
+ @Override
+ public String toString() {
+ return "InputValueData [uniqueId=" + uniqueId + ", hidden=" + hidden + ", type=" + type + ", creationTime="
+ + creationTime + ", value=" + value + ", modificationTime=" + modificationTime + "]";
+ }
+
+ public Boolean isHidden() {
+ return hidden;
+ }
+
+ public void setHidden(Boolean hidden) {
+ this.hidden = hidden;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java
new file mode 100644
index 0000000000..3bb71d5bed
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java
@@ -0,0 +1,149 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.Constants;
+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 com.google.gson.reflect.TypeToken;
+
+public class InputsData extends GraphNode {
+
+ PropertyDataDefinition propertyDataDefinition;
+
+ private List<String> constraints;
+
+ public InputsData() {
+ super(NodeTypeEnum.Input);
+ propertyDataDefinition = new PropertyDataDefinition();
+ }
+
+ public InputsData(PropertyDataDefinition propertyDataDefinition, List<String> constraints) {
+ super(NodeTypeEnum.Input);
+ this.propertyDataDefinition = propertyDataDefinition;
+ this.constraints = constraints;
+ }
+
+ public InputsData(Map<String, Object> properties) {
+
+ this();
+
+ propertyDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ propertyDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+
+ propertyDataDefinition.setRequired((Boolean) properties.get(GraphPropertiesDictionary.REQUIRED.getProperty()));
+
+ String defaultValue = (String) properties.get(GraphPropertiesDictionary.DEFAULT_VALUE.getProperty());
+ if (Constants.GRAPH_EMPTY_VALUE.equals(defaultValue)) {
+ propertyDataDefinition.setDefaultValue(null);
+ } else {
+ propertyDataDefinition.setDefaultValue(defaultValue);
+ }
+
+ propertyDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+
+ Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> constraintsfromJson = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.CONSTRAINTS.getProperty()), listType);
+ setConstraints(constraintsfromJson);
+ // setConstraints((List<String>)
+ // properties.get(GraphPropertiesDictionary.CONSTRAINTS.getProperty()));
+
+ Type schemaType = new TypeToken<SchemaDefinition>() {
+ }.getType();
+ SchemaDefinition schema = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.ENTRY_SCHEMA.getProperty()), schemaType);
+ propertyDataDefinition.setSchema(schema);
+
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, propertyDataDefinition.getUniqueId());
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, propertyDataDefinition.getType());
+
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, propertyDataDefinition.getDescription());
+
+ String defaultValue = propertyDataDefinition.getDefaultValue();
+ if (defaultValue == null) {
+ defaultValue = Constants.GRAPH_EMPTY_VALUE;
+ }
+ addIfExists(map, GraphPropertiesDictionary.DEFAULT_VALUE, defaultValue);
+
+ addIfExists(map, GraphPropertiesDictionary.REQUIRED, propertyDataDefinition.isRequired());
+
+ addIfExists(map, GraphPropertiesDictionary.CONSTRAINTS, getConstraints());
+
+ SchemaDefinition entrySchema = propertyDataDefinition.getSchema();
+ if (entrySchema != null) {
+ String entrySchemaStr = getGson().toJson(entrySchema);
+ addIfExists(map, GraphPropertiesDictionary.ENTRY_SCHEMA, entrySchemaStr);
+ }
+ // String constraintsAsJson = getGson().toJson(getConstraints());
+ // addIfExists(map, GraphPropertiesDictionary.CONSTRAINTS,
+ // constraintsAsJson);
+
+ return map;
+ }
+
+ public List<String> getConstraints() {
+ return constraints;
+ }
+
+ public void setConstraints(List<String> constraints) {
+ this.constraints = constraints;
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return propertyDataDefinition.getUniqueId();
+ }
+
+ public PropertyDataDefinition getPropertyDataDefinition() {
+ return propertyDataDefinition;
+ }
+
+ public void setPropertyDataDefinition(PropertyDataDefinition propertyDataDefinition) {
+ this.propertyDataDefinition = propertyDataDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "PropertyData [propertyDataDefinition=" + propertyDataDefinition + ", constraints=" + constraints + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InterfaceData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InterfaceData.java
new file mode 100644
index 0000000000..4ad07d70eb
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InterfaceData.java
@@ -0,0 +1,91 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class InterfaceData extends GraphNode {
+
+ private InterfaceDataDefinition interfaceDataDefinition;
+
+ public InterfaceData() {
+ super(NodeTypeEnum.Interface);
+ interfaceDataDefinition = new InterfaceDataDefinition();
+
+ }
+
+ public InterfaceData(InterfaceData p) {
+ super(NodeTypeEnum.Interface);
+ interfaceDataDefinition = p.getInterfaceDataDefinition();
+
+ }
+
+ public InterfaceData(InterfaceDataDefinition interfaceDataDefinition) {
+ super(NodeTypeEnum.Interface);
+ this.interfaceDataDefinition = interfaceDataDefinition;
+
+ }
+
+ public InterfaceData(Map<String, Object> properties) {
+ this();
+ interfaceDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ interfaceDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+ interfaceDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+ interfaceDataDefinition
+ .setCreationDate((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+ interfaceDataDefinition
+ .setLastUpdateDate((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+ }
+
+ public InterfaceDataDefinition getInterfaceDataDefinition() {
+ return interfaceDataDefinition;
+ }
+
+ public void setInterfaceDataDefinition(InterfaceDataDefinition interfaceDataDefinition) {
+ this.interfaceDataDefinition = interfaceDataDefinition;
+ }
+
+ @Override
+ public String getUniqueId() {
+ return interfaceDataDefinition.getUniqueId();
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, interfaceDataDefinition.getUniqueId());
+ addIfExists(map, GraphPropertiesDictionary.TYPE, interfaceDataDefinition.getType());
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, interfaceDataDefinition.getCreationDate());
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, interfaceDataDefinition.getLastUpdateDate());
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, interfaceDataDefinition.getDescription());
+
+ return map;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java
new file mode 100644
index 0000000000..d87cfe8853
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java
@@ -0,0 +1,88 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class OperationData extends GraphNode {
+
+ OperationDataDefinition operationDataDefinition;
+
+ protected OperationData() {
+ super(NodeTypeEnum.InterfaceOperation);
+ operationDataDefinition = new OperationDataDefinition();
+ }
+
+ public OperationData(OperationDataDefinition operationDataDefinition) {
+ super(NodeTypeEnum.InterfaceOperation);
+ this.operationDataDefinition = operationDataDefinition;
+
+ }
+
+ public OperationData(OperationData operationData) {
+ super(NodeTypeEnum.InterfaceOperation);
+ this.operationDataDefinition = operationData.getOperationDataDefinition();
+
+ }
+
+ public OperationData(Map<String, Object> properties) {
+ this();
+ operationDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ operationDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+ operationDataDefinition
+ .setCreationDate((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+ operationDataDefinition
+ .setLastUpdateDate((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+ }
+
+ public OperationDataDefinition getOperationDataDefinition() {
+ return operationDataDefinition;
+ }
+
+ public void setOperationDataDefinition(OperationDataDefinition operationDataDefinition) {
+ this.operationDataDefinition = operationDataDefinition;
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return operationDataDefinition.getUniqueId();
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, operationDataDefinition.getUniqueId());
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, operationDataDefinition.getCreationDate());
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, operationDataDefinition.getLastUpdateDate());
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, operationDataDefinition.getDescription());
+
+ return map;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java
new file mode 100644
index 0000000000..62f2ad5e12
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java
@@ -0,0 +1,130 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class PolicyTypeData extends GraphNode {
+
+ private PolicyTypeDataDefinition policyTypeDataDefinition;
+ private static final Type mapType = new TypeToken<HashMap<String, String>>() {
+ }.getType();
+ private static final Type listType = new TypeToken<List<String>>() {
+ }.getType();
+
+ public PolicyTypeData() {
+ super(NodeTypeEnum.PolicyType);
+ policyTypeDataDefinition = new PolicyTypeDataDefinition();
+ }
+
+ public PolicyTypeData(PolicyTypeDataDefinition policyTypeDataDefinition) {
+ super(NodeTypeEnum.PolicyType);
+ this.policyTypeDataDefinition = policyTypeDataDefinition;
+ }
+
+ public PolicyTypeData(Map<String, Object> properties) {
+
+ this();
+
+ policyTypeDataDefinition
+ .setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ HashMap<String, String> metatdata = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.METADATA.getProperty()), mapType);
+ policyTypeDataDefinition.setMetadata(metatdata);
+
+ List<String> members = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.TARGETS.getProperty()), listType);
+ policyTypeDataDefinition.setTargets(members);
+
+ policyTypeDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+
+ policyTypeDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+
+ policyTypeDataDefinition.setHighestVersion(
+ (boolean) properties.get(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()));
+
+ policyTypeDataDefinition.setVersion((String) properties.get(GraphPropertiesDictionary.VERSION.getProperty()));
+
+ policyTypeDataDefinition
+ .setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ policyTypeDataDefinition
+ .setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, policyTypeDataDefinition.getUniqueId());
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, policyTypeDataDefinition.getType());
+
+ addIfExists(map, GraphPropertiesDictionary.VERSION, policyTypeDataDefinition.getVersion());
+
+ addIfExists(map, GraphPropertiesDictionary.IS_HIGHEST_VERSION, policyTypeDataDefinition.isHighestVersion());
+
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, policyTypeDataDefinition.getDescription());
+
+ addIfExists(map, GraphPropertiesDictionary.METADATA, policyTypeDataDefinition.getMetadata());
+
+ addIfExists(map, GraphPropertiesDictionary.TARGETS, policyTypeDataDefinition.getTargets());
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, policyTypeDataDefinition.getCreationTime());
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, policyTypeDataDefinition.getModificationTime());
+
+ return map;
+ }
+
+ @Override
+ public String toString() {
+ return "PolicyTypeData [policyTypeDataDefinition=" + policyTypeDataDefinition + "]";
+ }
+
+ @Override
+ public String getUniqueId() {
+ return this.policyTypeDataDefinition.getUniqueId();
+ }
+
+ public PolicyTypeDataDefinition getPolicyTypeDataDefinition() {
+ return policyTypeDataDefinition;
+ }
+
+ public void setPolicyTypeDataDefinition(PolicyTypeDataDefinition policyTypeDataDefinition) {
+ this.policyTypeDataDefinition = policyTypeDataDefinition;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ProductMetadataData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ProductMetadataData.java
new file mode 100644
index 0000000000..9bf3ce2a03
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ProductMetadataData.java
@@ -0,0 +1,77 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.ProductMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class ProductMetadataData extends ComponentMetadataData {
+
+ public ProductMetadataData() {
+ super(NodeTypeEnum.Product, new ProductMetadataDataDefinition());
+ }
+
+ public ProductMetadataData(ProductMetadataDataDefinition metadataDataDefinition) {
+ super(NodeTypeEnum.Product, metadataDataDefinition);
+ }
+
+ public ProductMetadataData(Map<String, Object> properties) {
+ super(NodeTypeEnum.Product, new ProductMetadataDataDefinition(), properties);
+ ((ProductMetadataDataDefinition) metadataDataDefinition)
+ .setFullName((String) properties.get(GraphPropertiesDictionary.FULL_NAME.getProperty()));
+ Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> contactsfromJson = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.CONTACTS.getProperty()), listType);
+ ((ProductMetadataDataDefinition) metadataDataDefinition).setContacts(contactsfromJson);
+ ((ProductMetadataDataDefinition) metadataDataDefinition)
+ .setIsActive((Boolean) properties.get(GraphPropertiesDictionary.IS_ACTIVE.getProperty()));
+ }
+
+ @Override
+ public String getUniqueIdKey() {
+ return GraphPropertiesDictionary.UNIQUE_ID.getProperty();
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> graphMap = super.toGraphMap();
+ addIfExists(graphMap, GraphPropertiesDictionary.FULL_NAME,
+ ((ProductMetadataDataDefinition) metadataDataDefinition).getFullName());
+ addIfExists(graphMap, GraphPropertiesDictionary.CONTACTS,
+ ((ProductMetadataDataDefinition) metadataDataDefinition).getContacts());
+ addIfExists(graphMap, GraphPropertiesDictionary.IS_ACTIVE,
+ ((ProductMetadataDataDefinition) metadataDataDefinition).getIsActive());
+ return graphMap;
+ }
+
+ @Override
+ public String toString() {
+ return "ProductMetadataData [metadataDataDefinition=" + metadataDataDefinition + "]";
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java
new file mode 100644
index 0000000000..a72ec9465b
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java
@@ -0,0 +1,149 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.Constants;
+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 com.google.gson.reflect.TypeToken;
+
+public class PropertyData extends GraphNode {
+
+ PropertyDataDefinition propertyDataDefinition;
+
+ private List<String> constraints;
+
+ public PropertyData() {
+ super(NodeTypeEnum.Property);
+ propertyDataDefinition = new PropertyDataDefinition();
+ }
+
+ public PropertyData(PropertyDataDefinition propertyDataDefinition, List<String> constraints) {
+ super(NodeTypeEnum.Property);
+ this.propertyDataDefinition = propertyDataDefinition;
+ this.constraints = constraints;
+ }
+
+ public PropertyData(Map<String, Object> properties) {
+
+ this();
+
+ propertyDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ propertyDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+
+ propertyDataDefinition.setRequired((Boolean) properties.get(GraphPropertiesDictionary.REQUIRED.getProperty()));
+
+ String defaultValue = (String) properties.get(GraphPropertiesDictionary.DEFAULT_VALUE.getProperty());
+ if (Constants.GRAPH_EMPTY_VALUE.equals(defaultValue)) {
+ propertyDataDefinition.setDefaultValue(null);
+ } else {
+ propertyDataDefinition.setDefaultValue(defaultValue);
+ }
+
+ propertyDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+
+ Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> constraintsfromJson = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.CONSTRAINTS.getProperty()), listType);
+ setConstraints(constraintsfromJson);
+ // setConstraints((List<String>)
+ // properties.get(GraphPropertiesDictionary.CONSTRAINTS.getProperty()));
+
+ Type schemaType = new TypeToken<SchemaDefinition>() {
+ }.getType();
+ SchemaDefinition schema = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.ENTRY_SCHEMA.getProperty()), schemaType);
+ propertyDataDefinition.setSchema(schema);
+
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, propertyDataDefinition.getUniqueId());
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, propertyDataDefinition.getType());
+
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, propertyDataDefinition.getDescription());
+
+ String defaultValue = propertyDataDefinition.getDefaultValue();
+ if (defaultValue == null) {
+ defaultValue = Constants.GRAPH_EMPTY_VALUE;
+ }
+ addIfExists(map, GraphPropertiesDictionary.DEFAULT_VALUE, defaultValue);
+
+ addIfExists(map, GraphPropertiesDictionary.REQUIRED, propertyDataDefinition.isRequired());
+
+ addIfExists(map, GraphPropertiesDictionary.CONSTRAINTS, getConstraints());
+
+ SchemaDefinition entrySchema = propertyDataDefinition.getSchema();
+ if (entrySchema != null) {
+ String entrySchemaStr = getGson().toJson(entrySchema);
+ addIfExists(map, GraphPropertiesDictionary.ENTRY_SCHEMA, entrySchemaStr);
+ }
+ // String constraintsAsJson = getGson().toJson(getConstraints());
+ // addIfExists(map, GraphPropertiesDictionary.CONSTRAINTS,
+ // constraintsAsJson);
+
+ return map;
+ }
+
+ public List<String> getConstraints() {
+ return constraints;
+ }
+
+ public void setConstraints(List<String> constraints) {
+ this.constraints = constraints;
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return propertyDataDefinition.getUniqueId();
+ }
+
+ public PropertyDataDefinition getPropertyDataDefinition() {
+ return propertyDataDefinition;
+ }
+
+ public void setPropertyDataDefinition(PropertyDataDefinition propertyDataDefinition) {
+ this.propertyDataDefinition = propertyDataDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "PropertyData [propertyDataDefinition=" + propertyDataDefinition + ", constraints=" + constraints + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java
new file mode 100644
index 0000000000..7577e57a7e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java
@@ -0,0 +1,158 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.Constants;
+import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class PropertyValueData extends GraphNode {
+
+ public PropertyValueData() {
+ super(NodeTypeEnum.PropertyValue);
+ }
+
+ public PropertyValueData(Map<String, Object> properties) {
+ this();
+
+ this.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ String updatedValue = (String) properties.get(GraphPropertiesDictionary.VALUE.getProperty());
+ if (Constants.GRAPH_EMPTY_VALUE.equals(updatedValue)) {
+ this.setValue(null);
+ } else {
+ this.setValue(updatedValue);
+ }
+
+ this.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+
+ this.setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ this.setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ Type mapType = new TypeToken<List<PropertyRule>>() {
+ }.getType();
+ List<PropertyRule> propertyRules = getGson().fromJson(
+ (String) properties.get(GraphPropertiesDictionary.PROPERTY_VALUE_RULES.getProperty()), mapType);
+ this.setRules(propertyRules);
+
+ }
+
+ private String uniqueId;
+
+ private String value;
+
+ private String type;
+
+ private Long creationTime;
+
+ private Long modificationTime;
+
+ private List<PropertyRule> rules;
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public Long getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(Long creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public Long getModificationTime() {
+ return modificationTime;
+ }
+
+ public void setModificationTime(Long modificationTime) {
+ this.modificationTime = modificationTime;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public List<PropertyRule> getRules() {
+ return rules;
+ }
+
+ public void setRules(List<PropertyRule> rules) {
+ this.rules = rules;
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+
+ String updatedValue = value;
+ if (updatedValue == null) {
+ updatedValue = Constants.GRAPH_EMPTY_VALUE;
+ }
+ addIfExists(map, GraphPropertiesDictionary.VALUE, updatedValue);
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, type);
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, creationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, modificationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.PROPERTY_VALUE_RULES, rules);
+
+ return map;
+ }
+
+ @Override
+ public String toString() {
+ return "PropertyValueData [uniqueId=" + uniqueId + ", value=" + value + ", type=" + type + ", creationTime="
+ + creationTime + ", modificationTime=" + modificationTime + ", rules=" + rules + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipInstData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipInstData.java
new file mode 100644
index 0000000000..7fc9a601c9
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipInstData.java
@@ -0,0 +1,164 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class RelationshipInstData extends GraphNode {
+
+ private String type;
+
+ private String uniqueId;
+
+ private Long creationTime;
+
+ private Long modificationTime;
+
+ private String capabilityOwnerId;
+ private String requirementOwnerId;
+ private String capabiltyId;
+ private String requirementId;
+
+ public RelationshipInstData() {
+ super(NodeTypeEnum.RelationshipInst);
+ }
+
+ public RelationshipInstData(Map<String, Object> properties) {
+
+ this();
+
+ this.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+
+ this.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ this.setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ this.setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ this.setCapabilityOwnerId((String) properties.get(GraphPropertiesDictionary.CAPABILITY_OWNER_ID.getProperty()));
+ this.setRequirementOwnerId(
+ (String) properties.get(GraphPropertiesDictionary.REQUIREMENT_OWNER_ID.getProperty()));
+ this.setRequirementId((String) properties.get(GraphPropertiesDictionary.REQUIREMENT_ID.getProperty()));
+ this.setCapabiltyId((String) properties.get(GraphPropertiesDictionary.CAPABILITY_ID.getProperty()));
+
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, type);
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, creationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, modificationTime);
+ addIfExists(map, GraphPropertiesDictionary.CAPABILITY_OWNER_ID, capabilityOwnerId);
+ addIfExists(map, GraphPropertiesDictionary.REQUIREMENT_OWNER_ID, requirementOwnerId);
+
+ addIfExists(map, GraphPropertiesDictionary.REQUIREMENT_ID, requirementId);
+
+ addIfExists(map, GraphPropertiesDictionary.CAPABILITY_ID, capabiltyId);
+
+ return map;
+ }
+
+ public Long getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(Long creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public Long getModificationTime() {
+ return modificationTime;
+ }
+
+ public void setModificationTime(Long modificationTime) {
+ this.modificationTime = modificationTime;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ @Override
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getCapabilityOwnerId() {
+ return capabilityOwnerId;
+ }
+
+ public void setCapabilityOwnerId(String capabilityOwnerId) {
+ this.capabilityOwnerId = capabilityOwnerId;
+ }
+
+ public String getRequirementOwnerId() {
+ return requirementOwnerId;
+ }
+
+ public void setRequirementOwnerId(String requirementOwnerId) {
+ this.requirementOwnerId = requirementOwnerId;
+ }
+
+ public String getCapabiltyId() {
+ return capabiltyId;
+ }
+
+ public void setCapabiltyId(String capabiltyId) {
+ this.capabiltyId = capabiltyId;
+ }
+
+ public String getRequirementId() {
+ return requirementId;
+ }
+
+ public void setRequirementId(String requirementId) {
+ this.requirementId = requirementId;
+ }
+
+ @Override
+ public String toString() {
+ return "RelationshipInstData [type=" + type + ", uniqueId=" + uniqueId + ", creationTime=" + creationTime
+ + ", modificationTime=" + modificationTime + ", capabilityOwnerId=" + capabilityOwnerId
+ + ", requirementOwnerId=" + requirementOwnerId + ", capabiltyId=" + capabiltyId + ", requirementId="
+ + requirementId + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java
new file mode 100644
index 0000000000..7ceecf7e21
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java
@@ -0,0 +1,128 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.elements.RelationshipTypeDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class RelationshipTypeData extends GraphNode {
+
+ RelationshipTypeDataDefinition relationshipTypeDataDefinition;
+
+ public RelationshipTypeData() {
+ super(NodeTypeEnum.RelationshipType);
+ relationshipTypeDataDefinition = new RelationshipTypeDataDefinition();
+ }
+
+ public RelationshipTypeData(RelationshipTypeDataDefinition relationshipTypeDataDefinition) {
+ super(NodeTypeEnum.RelationshipType);
+ this.relationshipTypeDataDefinition = relationshipTypeDataDefinition;
+ }
+
+ public RelationshipTypeData(Map<String, Object> properties) {
+
+ this();
+
+ relationshipTypeDataDefinition
+ .setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ relationshipTypeDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+
+ relationshipTypeDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+
+ Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> validSourceTypesfromJson = getGson().fromJson(
+ (String) properties.get(GraphPropertiesDictionary.VALID_SOURCE_TYPES.getProperty()), listType);
+
+ relationshipTypeDataDefinition.setValidSourceTypes(validSourceTypesfromJson);
+
+ // relationshipTypeDataDefinition.setValidSourceTypes((List<String>)
+ // properties.get(GraphPropertiesDictionary.VALID_SOURCE_TYPES
+ // .getProperty()));
+
+ relationshipTypeDataDefinition
+ .setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ relationshipTypeDataDefinition
+ .setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ // capabilityTypeDataDefinition.setVersion(version);
+
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, relationshipTypeDataDefinition.getUniqueId());
+
+ addIfExists(map, GraphPropertiesDictionary.TYPE, relationshipTypeDataDefinition.getType());
+
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, relationshipTypeDataDefinition.getDescription());
+
+ // String validSourceTypesToJson =
+ // getGson().toJson(relationshipTypeDataDefinition.getValidSourceTypes());
+
+ // addIfExists(map, GraphPropertiesDictionary.VALID_SOURCE_TYPES,
+ // validSourceTypesToJson);
+
+ addIfExists(map, GraphPropertiesDictionary.VALID_SOURCE_TYPES,
+ relationshipTypeDataDefinition.getValidSourceTypes());
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, relationshipTypeDataDefinition.getCreationTime());
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE,
+ relationshipTypeDataDefinition.getModificationTime());
+
+ return map;
+ }
+
+ public RelationshipTypeDataDefinition getRelationshipTypeDataDefinition() {
+ return relationshipTypeDataDefinition;
+ }
+
+ public void setRelationshipTypeDataDefinition(RelationshipTypeDataDefinition relationshipTypeDataDefinition) {
+ this.relationshipTypeDataDefinition = relationshipTypeDataDefinition;
+ }
+
+ @Override
+ public String getUniqueId() {
+ return this.relationshipTypeDataDefinition.getUniqueId();
+ }
+
+ @Override
+ public String toString() {
+ return "RelationshipTypeData [relationshipTypeDataDefinition=" + relationshipTypeDataDefinition + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java
new file mode 100644
index 0000000000..2b7e2d22b7
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java
@@ -0,0 +1,158 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class RequirementData extends GraphNode {
+ public final static String MIN_OCCURRENCES = "1";
+ public final static String MAX_OCCURRENCES = "UNBOUNDED";
+ public final static String MAX_DEFAULT_OCCURRENCES = "1";
+
+ private String uniqueId;
+
+ private String node;
+
+ private Long creationTime;
+
+ private Long modificationTime;
+
+ private String relationshipType;
+ private String minOccurrences = MIN_OCCURRENCES;
+ private String maxOccurrences = MAX_DEFAULT_OCCURRENCES;
+
+ public RequirementData() {
+ super(NodeTypeEnum.Requirement);
+
+ }
+
+ public RequirementData(Map<String, Object> properties) {
+
+ this();
+
+ this.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ this.setNode((String) properties.get(GraphPropertiesDictionary.NODE.getProperty()));
+
+ this.setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ this.setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ this.setRelationshipType((String) properties.get(GraphPropertiesDictionary.RELATIONSHIP_TYPE.getProperty()));
+ this.setMinOccurrences((String) properties.get(GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty()));
+ this.setMaxOccurrences((String) properties.get(GraphPropertiesDictionary.MAX_OCCURRENCES.getProperty()));
+
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+
+ addIfExists(map, GraphPropertiesDictionary.NODE, node);
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, creationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, modificationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.RELATIONSHIP_TYPE, relationshipType);
+ addIfExists(map, GraphPropertiesDictionary.MIN_OCCURRENCES, minOccurrences);
+ addIfExists(map, GraphPropertiesDictionary.MAX_OCCURRENCES, maxOccurrences);
+
+ return map;
+ }
+
+ public String getNode() {
+ return node;
+ }
+
+ public void setNode(String node) {
+ this.node = node;
+ }
+
+ public Long getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(Long creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public Long getModificationTime() {
+ return modificationTime;
+ }
+
+ public void setModificationTime(Long modificationTime) {
+ this.modificationTime = modificationTime;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public String getRelationshipType() {
+ return relationshipType;
+ }
+
+ public void setRelationshipType(String relationshipType) {
+ this.relationshipType = relationshipType;
+ }
+
+ public String getMinOccurrences() {
+ return minOccurrences;
+ }
+
+ public void setMinOccurrences(String minOccurrences) {
+ if (minOccurrences != null) {
+ this.minOccurrences = minOccurrences;
+ }
+ }
+
+ public String getMaxOccurrences() {
+ return maxOccurrences;
+ }
+
+ public void setMaxOccurrences(String maxOccurrences) {
+ if (maxOccurrences != null) {
+ this.maxOccurrences = maxOccurrences;
+ }
+ }
+
+ @Override
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ @Override
+ public String toString() {
+ return "RequirementData [uniqueId=" + uniqueId + ", node=" + node + ", creationTime=" + creationTime
+ + ", modificationTime=" + modificationTime + ", relationshipType=" + relationshipType
+ + ", minOccurrences=" + minOccurrences + ", maxOccurrences=" + maxOccurrences + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementImplData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementImplData.java
new file mode 100644
index 0000000000..1224f873d2
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementImplData.java
@@ -0,0 +1,141 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class RequirementImplData extends GraphNode {
+
+ private String name;
+
+ private String uniqueId;
+
+ private Long creationTime;
+
+ private Long modificationTime;
+
+ private String posX;
+
+ private String posY;
+
+ public RequirementImplData() {
+ super(NodeTypeEnum.RequirementImpl);
+ }
+
+ public RequirementImplData(Map<String, Object> properties) {
+
+ this();
+
+ this.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+
+ this.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+
+ this.setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+
+ this.setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+
+ setPosX((String) properties.get(GraphPropertiesDictionary.POSITION_X.getProperty()));
+
+ setPosY((String) properties.get(GraphPropertiesDictionary.POSITION_Y.getProperty()));
+
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+
+ addIfExists(map, GraphPropertiesDictionary.NAME, name);
+
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, creationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, modificationTime);
+
+ addIfExists(map, GraphPropertiesDictionary.POSITION_X, posX);
+
+ addIfExists(map, GraphPropertiesDictionary.POSITION_Y, posY);
+
+ return map;
+ }
+
+ public Long getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(Long creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public Long getModificationTime() {
+ return modificationTime;
+ }
+
+ public void setModificationTime(Long modificationTime) {
+ this.modificationTime = modificationTime;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ @Override
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getPosX() {
+ return posX;
+ }
+
+ public void setPosX(String posX) {
+ this.posX = posX;
+ }
+
+ public String getPosY() {
+ return posY;
+ }
+
+ public void setPosY(String posY) {
+ this.posY = posY;
+ }
+
+ @Override
+ public String toString() {
+ return "RequirementImplData [name=" + name + ", uniqueId=" + uniqueId + ", creationTime=" + creationTime
+ + ", modificationTime=" + modificationTime + ", posX=" + posX + ", posY=" + posY + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceCategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceCategoryData.java
new file mode 100644
index 0000000000..012780c5a7
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceCategoryData.java
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class ResourceCategoryData extends CategoryData {
+
+ private String categoryName;
+
+ public ResourceCategoryData() {
+ super(NodeTypeEnum.ResourceCategory);
+ }
+
+ public ResourceCategoryData(String categoryName, String name) {
+ super(name, "", NodeTypeEnum.ResourceCategory);
+ this.categoryName = categoryName;
+ createUniqueId();
+ }
+
+ public ResourceCategoryData(Map<String, Object> properties) {
+ super(properties, NodeTypeEnum.ResourceCategory);
+ setCategoryName((String) properties.get(GraphPropertiesDictionary.CATEGORY_NAME.getProperty()));
+ }
+
+ public String getCategoryName() {
+ return categoryName;
+ }
+
+ public void setCategoryName(String categoryName) {
+ this.categoryName = categoryName;
+ }
+
+ @Override
+ protected void createUniqueId() {
+ setUniqueId(getLabel() + "." + this.categoryName + "." + getName());
+ }
+
+ @Override
+ public String toString() {
+ return "ResourceCategoryData [categoryName=" + categoryName + "]" + super.toString();
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> graphMap = super.toGraphMap();
+ addIfExists(graphMap, GraphPropertiesDictionary.CATEGORY_NAME, categoryName);
+ return graphMap;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java
new file mode 100644
index 0000000000..9df3d7cfac
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java
@@ -0,0 +1,80 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+
+public class ResourceMetadataData extends ComponentMetadataData {
+
+ public ResourceMetadataData() {
+ super(NodeTypeEnum.Resource, new ResourceMetadataDataDefinition());
+ }
+
+ public ResourceMetadataData(ComponentMetadataDataDefinition metadataDataDefinition) {
+ super(NodeTypeEnum.Resource, metadataDataDefinition);
+ }
+
+ public ResourceMetadataData(Map<String, Object> properties) {
+ super(NodeTypeEnum.Resource, new ResourceMetadataDataDefinition(), properties);
+ ((ResourceMetadataDataDefinition) metadataDataDefinition)
+ .setVendorName((String) properties.get(GraphPropertiesDictionary.VENDOR_NAME.getProperty()));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition)
+ .setVendorRelease((String) properties.get(GraphPropertiesDictionary.VENDOR_RELEASE.getProperty()));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).setResourceType(ResourceTypeEnum
+ .valueOf((String) properties.get(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty())));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition)
+ .setAbstract((Boolean) properties.get(GraphPropertiesDictionary.IS_ABSTRACT.getProperty()));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition)
+ .setCost((String) properties.get(GraphPropertiesDictionary.COST.getProperty()));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition)
+ .setLicenseType((String) properties.get(GraphPropertiesDictionary.LICENSE_TYPE.getProperty()));
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).setToscaResourceName(
+ (String) properties.get(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty()));
+
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> graphMap = super.toGraphMap();
+ addIfExists(graphMap, GraphPropertiesDictionary.VENDOR_NAME,
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).getVendorName());
+ addIfExists(graphMap, GraphPropertiesDictionary.VENDOR_RELEASE,
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).getVendorRelease());
+ addIfExists(graphMap, GraphPropertiesDictionary.RESOURCE_TYPE,
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).getResourceType().name());
+ addIfExists(graphMap, GraphPropertiesDictionary.IS_ABSTRACT,
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).isAbstract());
+ addIfExists(graphMap, GraphPropertiesDictionary.COST,
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).getCost());
+ addIfExists(graphMap, GraphPropertiesDictionary.LICENSE_TYPE,
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).getLicenseType());
+ addIfExists(graphMap, GraphPropertiesDictionary.TOSCA_RESOURCE_NAME,
+ ((ResourceMetadataDataDefinition) metadataDataDefinition).getToscaResourceName());
+ return graphMap;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceArtifactsDataCollection.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceArtifactsDataCollection.java
new file mode 100644
index 0000000000..6d01268434
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceArtifactsDataCollection.java
@@ -0,0 +1,45 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.List;
+import java.util.Map;
+
+public class ServiceArtifactsDataCollection {
+
+ private Map<String, List<ESArtifactData>> serviceArtifactDataMap;
+
+ public Map<String, List<ESArtifactData>> getServiceArtifactDataMap() {
+ return serviceArtifactDataMap;
+ }
+
+ public void setServiceArtifactDataMap(Map<String, List<ESArtifactData>> serviceArtifactDataMap) {
+ this.serviceArtifactDataMap = serviceArtifactDataMap;
+ }
+
+ public List<ESArtifactData> getNodeTemplateArtifacts(String nodeTemplateName) {
+ if (serviceArtifactDataMap != null && serviceArtifactDataMap.containsKey(nodeTemplateName))
+ return serviceArtifactDataMap.get(nodeTemplateName);
+ else
+ return null;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceCategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceCategoryData.java
new file mode 100644
index 0000000000..666e2e51b6
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceCategoryData.java
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.Map;
+
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class ServiceCategoryData extends CategoryData {
+
+ public ServiceCategoryData() {
+ super(NodeTypeEnum.ServiceCategory);
+ }
+
+ public ServiceCategoryData(String categoryName) {
+ super(categoryName, "", NodeTypeEnum.ServiceCategory);
+ createUniqueId();
+ }
+
+ public ServiceCategoryData(Map<String, Object> properties) {
+ super(properties, NodeTypeEnum.ServiceCategory);
+ }
+
+ @Override
+ protected void createUniqueId() {
+ setUniqueId(getLabel() + "." + getName());
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceMetadataData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceMetadataData.java
new file mode 100644
index 0000000000..12f011d72f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceMetadataData.java
@@ -0,0 +1,62 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class ServiceMetadataData extends ComponentMetadataData {
+
+ public ServiceMetadataData() {
+ super(NodeTypeEnum.Service, new ServiceMetadataDataDefinition());
+ }
+
+ public ServiceMetadataData(ServiceMetadataDataDefinition serviceMetadataDataDefinition) {
+ super(NodeTypeEnum.Service, serviceMetadataDataDefinition);
+ }
+
+ public ServiceMetadataData(Map<String, Object> properties) {
+ super(NodeTypeEnum.Service, new ServiceMetadataDataDefinition(), properties);
+ ((ServiceMetadataDataDefinition) metadataDataDefinition)
+ .setProjectCode((String) properties.get(GraphPropertiesDictionary.PROJECT_CODE.getProperty()));
+ ((ServiceMetadataDataDefinition) metadataDataDefinition).setDistributionStatus(
+ (String) properties.get(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty()));
+ }
+
+ @Override
+ public String getUniqueIdKey() {
+ return GraphPropertiesDictionary.UNIQUE_ID.getProperty();
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> graphMap = super.toGraphMap();
+ addIfExists(graphMap, GraphPropertiesDictionary.PROJECT_CODE,
+ ((ServiceMetadataDataDefinition) metadataDataDefinition).getProjectCode());
+ addIfExists(graphMap, GraphPropertiesDictionary.DISTRIBUTION_STATUS,
+ ((ServiceMetadataDataDefinition) metadataDataDefinition).getDistributionStatus());
+ return graphMap;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java
new file mode 100644
index 0000000000..de2412d7ed
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java
@@ -0,0 +1,112 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class TagData extends GraphNode {
+
+ private String name;
+
+ protected TagData(NodeTypeEnum label) {
+ super(label);
+ }
+
+ public TagData(String name) {
+ super(NodeTypeEnum.Tag);
+ this.name = name;
+ }
+
+ public TagData() {
+ super(NodeTypeEnum.Tag);
+ }
+
+ public TagData(Map<String, Object> properties) {
+ super(NodeTypeEnum.Tag);
+ setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+ addIfExists(map, GraphPropertiesDictionary.NAME, name);
+ return map;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return "Tag [Name=" + name + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ TagData other = (TagData) obj;
+ if (name == null) {
+ if (other.getClass() != null) {
+ return false;
+ }
+ } else if (!name.equals(other.getName())) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String getUniqueIdKey() {
+ return GraphPropertiesDictionary.NAME.getProperty();
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return name;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java
new file mode 100644
index 0000000000..30f9a66d79
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class UniqueIdData extends GraphNode {
+
+ private String uniqueId;
+
+ public UniqueIdData(NodeTypeEnum label, String uniqueId) {
+ super(label);
+ this.uniqueId = uniqueId;
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return uniqueId;
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ return null;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java
new file mode 100644
index 0000000000..d09caacabe
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java
@@ -0,0 +1,228 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.DaoUtils;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class UserData extends GraphNode {
+
+ private String firstName;
+
+ private String lastName;
+
+ private String userId;
+
+ private String email;
+
+ private String role;
+
+ private String status;
+
+ private Long lastLoginTime;
+
+ public UserData(String firstName, String lastName, String userId, String email, String role, String status,
+ Long lastLoginTime) {
+ super(NodeTypeEnum.User);
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.userId = userId;
+ this.email = email;
+ this.role = role;
+ this.status = status;
+ this.lastLoginTime = lastLoginTime;
+ }
+
+ public UserData() {
+ super(NodeTypeEnum.User);
+ }
+
+ public UserData(Map<String, Object> properties) {
+ super(NodeTypeEnum.User);
+
+ setFirstName((String) properties.get("firstName"));
+ setLastName((String) properties.get("lastName"));
+ setUserId((String) properties.get("userId"));
+ setEmail((String) properties.get("email"));
+ setRole((String) properties.get("role"));
+ setStatus((String) properties.get("status"));
+ setLastLoginTime((Long) properties.get("lastLoginTime"));
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public String getUserId() {
+ return userId;
+ }
+
+ public void setUserId(String userId) {
+ this.userId = userId;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ // right name?
+ public void setLastLoginTime() {
+ Date d = new Date();
+ this.lastLoginTime = new Long(d.getTime()); // this is in milli-seconds
+ // divide by 1000 to get
+ // secs?
+ }
+
+ public void setLastLoginTime(Long time) {
+ this.lastLoginTime = time;
+ }
+
+ public Long getLastLoginTime() {
+ return this.lastLoginTime;
+ }
+
+ @Override
+ public String toString() {
+ return "UserData [firstName=" + firstName + ", lastName=" + lastName + ", userId=" + userId + ", email=" + email
+ + ", role=" + role + ", last Login time=" + lastLoginTime + ", parent: " + super.toString() + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((userId == null) ? 0 : userId.hashCode());
+ result = prime * result + ((email == null) ? 0 : email.hashCode());
+ result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
+ result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
+ result = prime * result + ((role == null) ? 0 : role.hashCode());
+ result = prime * result + ((lastLoginTime == null) ? 0 : lastLoginTime.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ UserData other = (UserData) obj;
+ if (userId == null) {
+ if (other.userId != null)
+ return false;
+ } else if (!userId.equals(other.userId))
+ return false;
+ if (email == null) {
+ if (other.email != null)
+ return false;
+ } else if (!email.equals(other.email))
+ return false;
+ if (firstName == null) {
+ if (other.firstName != null)
+ return false;
+ } else if (!firstName.equals(other.firstName))
+ return false;
+ if (lastName == null) {
+ if (other.lastName != null)
+ return false;
+ } else if (!lastName.equals(other.lastName))
+ return false;
+ if (role == null) {
+ if (other.role != null)
+ return false;
+ } else if (!role.equals(other.role))
+ return false;
+ if (lastLoginTime == null) {
+ if (other.lastLoginTime != null)
+ return false;
+ } else if (!lastLoginTime.equals(other.lastLoginTime))
+ return false;
+ return true;
+ }
+
+ public String toJson() {
+ return DaoUtils.convertToJson(toGraphMap());
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+ addIfExists(map, GraphPropertiesDictionary.USER_ID, userId);
+ addIfExists(map, GraphPropertiesDictionary.EMAIL, email);
+ addIfExists(map, GraphPropertiesDictionary.FIRST_NAME, firstName);
+ addIfExists(map, GraphPropertiesDictionary.LAST_NAME, lastName);
+ addIfExists(map, GraphPropertiesDictionary.ROLE, role);
+ addIfExists(map, GraphPropertiesDictionary.USER_STATUS, status);
+ addIfExists(map, GraphPropertiesDictionary.LAST_LOGIN_TIME, lastLoginTime);
+ return map;
+ }
+
+ @Override
+ public String getUniqueIdKey() {
+ return GraphPropertiesDictionary.USER_ID.getProperty();
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return userId;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java
new file mode 100644
index 0000000000..2a31f4bb68
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java
@@ -0,0 +1,95 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.DaoUtils;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class UserFunctionalMenuData extends GraphNode {
+
+ private String uniqueId;
+
+ private String functionalMenu;
+
+ public UserFunctionalMenuData(String functionalMenu, String uniqueId) {
+ super(NodeTypeEnum.UserFunctionalMenu);
+ this.functionalMenu = functionalMenu;
+ this.uniqueId = uniqueId;
+ }
+
+ public UserFunctionalMenuData() {
+ super(NodeTypeEnum.UserFunctionalMenu);
+ }
+
+ public UserFunctionalMenuData(Map<String, Object> properties) {
+ super(NodeTypeEnum.UserFunctionalMenu);
+
+ setFunctionalMenu((String) properties.get(GraphPropertiesDictionary.FUNCTIONAL_MENU.getProperty()));
+ setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ }
+
+ public String getFunctionalMenu() {
+ return functionalMenu;
+ }
+
+ public void setFunctionalMenu(String functionalMenu) {
+ this.functionalMenu = functionalMenu;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ @Override
+ public String toString() {
+ return "UserFunctionalMenuData [uniqueId=" + uniqueId + ", functionalMenu=" + functionalMenu + "]";
+ }
+
+ public String toJson() {
+ return DaoUtils.convertToJson(toGraphMap());
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId);
+ addIfExists(map, GraphPropertiesDictionary.FUNCTIONAL_MENU, functionalMenu);
+
+ return map;
+ }
+
+ @Override
+ public String getUniqueIdKey() {
+ return GraphPropertiesDictionary.UNIQUE_ID.getProperty();
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return uniqueId;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java
new file mode 100644
index 0000000000..9e9836049f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java
@@ -0,0 +1,84 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.util.EnumMap;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+public final class AuditRecordFactory {
+ public static AuditingGenericEvent createAuditRecord(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ AuditingActionEnum actionEnum = AuditingActionEnum
+ .getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION));
+ String tableName = actionEnum.getAuditingEsType();
+ AuditingGenericEvent event = null;
+ switch (tableName) {
+ case AuditingTypesConstants.USER_ADMIN_EVENT_TYPE:
+ event = new UserAdminEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.AUTH_EVENT_TYPE:
+ event = new AuthEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.CATEGORY_EVENT_TYPE:
+ event = new CategoryEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE:
+ event = new ResourceAdminEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.USER_ACCESS_EVENT_TYPE:
+ event = new UserAccessEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.DISTRIBUTION_STATUS_EVENT_TYPE:
+ event = new DistributionStatusEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.DISTRIBUTION_DOWNLOAD_EVENT_TYPE:
+ event = new DistributionDownloadEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE:
+ event = new DistributionEngineEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.DISTRIBUTION_NOTIFICATION_EVENT_TYPE:
+ event = new DistributionNotificationEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE:
+ event = new DistributionDeployEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE:
+ event = new AuditingGetUebClusterEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.CONSUMER_EVENT_TYPE:
+ event = new ConsumerEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.GET_USERS_LIST_EVENT_TYPE:
+ event = new GetUsersListEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.GET_CATEGORY_HIERARCHY_EVENT_TYPE:
+ event = new GetCategoryHierarchyEvent(auditingFields);
+ break;
+ case AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE:
+ event = new ExternalApiEvent(auditingFields);
+ break;
+ }
+
+ return event;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java
new file mode 100644
index 0000000000..8b0bd58d9e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java
@@ -0,0 +1,135 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public enum AuditingActionEnum {
+
+ // User admininstration
+ ADD_USER("AddUser", AuditingTypesConstants.USER_ADMIN_EVENT_TYPE),
+ UPDATE_USER("UpdateUser", AuditingTypesConstants.USER_ADMIN_EVENT_TYPE),
+ DELETE_USER("DeleteUser", AuditingTypesConstants.USER_ADMIN_EVENT_TYPE),
+ USER_ACCESS("Access", AuditingTypesConstants.USER_ACCESS_EVENT_TYPE),
+ GET_USERS_LIST("GetUsersList", AuditingTypesConstants.GET_USERS_LIST_EVENT_TYPE),
+
+ // Resource/service administration
+ CREATE_RESOURCE("Create", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ IMPORT_RESOURCE("ResourceImport", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ CHECKOUT_RESOURCE("Checkout", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ UNDO_CHECKOUT_RESOURCE("UndoCheckout", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ CHECKIN_RESOURCE("Checkin", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ CERTIFICATION_REQUEST_RESOURCE("CertificationRequest", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ START_CERTIFICATION_RESOURCE("CertificationStart", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ FAIL_CERTIFICATION_RESOURCE("CertificationFailure", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ CANCEL_CERTIFICATION_RESOURCE("CertificationCancel", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ CERTIFICATION_SUCCESS_RESOURCE("CertificationSuccess", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ UPDATE_RESOURCE_METADATA("UpdateResourceMetadata", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ UPDATE_SERVICE_METADATA("UpdateServiceMetadata", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ ARTIFACT_UPLOAD("ArtifactUpload", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ ARTIFACT_UPLOAD_BY_API("ArtifactUploadByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
+ ARTIFACT_UPDATE_BY_API("ArtifactUpdateByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
+ ARTIFACT_DELETE_BY_API("ArtifactDeleteByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
+ ARTIFACT_PAYLOAD_UPDATE("ArtifactPayloadUpdate", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ ARTIFACT_METADATA_UPDATE("ArtifactMetadataUpdate", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ ARTIFACT_DELETE("ArtifactDelete", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ ARTIFACT_DOWNLOAD("ArtifactDownload", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ DOWNLOAD_ARTIFACT("DownloadArtifact",AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
+
+ // Distribution
+ DISTRIBUTION_ARTIFACT_DOWNLOAD("DArtifactDownload", AuditingTypesConstants.DISTRIBUTION_DOWNLOAD_EVENT_TYPE),
+ DISTRIBUTION_STATE_CHANGE_REQUEST("DRequest", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ DISTRIBUTION_STATE_CHANGE_APPROV("DApprove", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ DISTRIBUTION_STATE_CHANGE_REJECT("DReject", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
+ CREATE_DISTRIBUTION_TOPIC("CreateDistributionTopic", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE),
+ ADD_KEY_TO_TOPIC_ACL("AddKeyToTopicACL", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE),
+ REMOVE_KEY_FROM_TOPIC_ACL("RemoveKeyFromTopicACL", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE),
+ DISTRIBUTION_REGISTER("DRegister", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE),
+ DISTRIBUTION_UN_REGISTER("DUnRegister", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE),
+ DISTRIBUTION_NOTIFY("DNotify", AuditingTypesConstants.DISTRIBUTION_NOTIFICATION_EVENT_TYPE),
+ DISTRIBUTION_STATUS("DStatus", AuditingTypesConstants.DISTRIBUTION_STATUS_EVENT_TYPE),
+ DISTRIBUTION_DEPLOY("DResult",AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE),
+ GET_UEB_CLUSTER("GetUebCluster", AuditingTypesConstants.DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE),
+ GET_VALID_ARTIFACT_TYPES("GetValidArtifactTypes", AuditingTypesConstants.DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE),
+ // ....
+ AUTH_REQUEST("HttpAuthentication", AuditingTypesConstants.AUTH_EVENT_TYPE),
+ ADD_ECOMP_USER_CREDENTIALS("AddECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE),
+ GET_ECOMP_USER_CREDENTIALS("GetECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE),
+ DELETE_ECOMP_USER_CREDENTIALS("DeleteECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE),
+ UPDATE_ECOMP_USER_CREDENTIALS("UpdateECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE),
+ // Category
+ ADD_CATEGORY("AddCategory", AuditingTypesConstants.CATEGORY_EVENT_TYPE),
+ ADD_SUB_CATEGORY("AddSubCategory", AuditingTypesConstants.CATEGORY_EVENT_TYPE),
+ ADD_GROUPING("AddGrouping", AuditingTypesConstants.CATEGORY_EVENT_TYPE),
+ GET_CATEGORY_HIERARCHY("GetCategoryHierarchy", AuditingTypesConstants.GET_CATEGORY_HIERARCHY_EVENT_TYPE),
+
+ // Assets
+
+ GET_ASSET_LIST("GetAssetList", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
+ GET_FILTERED_ASSET_LIST("GetFilteredAssetList", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
+ GET_ASSET_METADATA("GetAssetMetadata", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
+ GET_TOSCA_MODEL("GetToscaModel", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE);
+
+ private String name;
+ // private Class<? extends AuditingGenericEvent> auditingEsType;
+ private String auditingEsType;
+
+ private static Logger log = LoggerFactory.getLogger(AuditingActionEnum.class.getName());
+
+ // AuditingActionEnum(String name, Class<? extends AuditingGenericEvent>
+ // auditingEsType){
+ // this.name = name;
+ // this.auditingEsType = auditingEsType;
+ // }
+
+ AuditingActionEnum(String name, String auditingEsType) {
+ this.name = name;
+ this.auditingEsType = auditingEsType;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ // public Class<? extends AuditingGenericEvent> getAuditingEsType(){
+ // return auditingEsType;
+ // }
+
+ public String getAuditingEsType() {
+ return auditingEsType;
+ }
+
+ public static AuditingActionEnum getActionByName(String name) {
+ AuditingActionEnum res = null;
+ AuditingActionEnum[] values = values();
+ for (AuditingActionEnum value : values) {
+ if (value.getName().equals(name)) {
+ res = value;
+ break;
+ }
+ }
+ if (res == null) {
+ log.debug("No auditing action is mapped to name {}", name);
+ }
+ return res;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGenericEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGenericEvent.java
new file mode 100644
index 0000000000..9e220bf8da
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGenericEvent.java
@@ -0,0 +1,91 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent;
+
+public class AuditingGenericEvent extends ESTimeBasedEvent {
+ protected String requestId;
+ protected String serviceInstanceId;
+ protected String action;
+ protected String status;
+
+ protected String desc;
+
+ // protected Map<String, Object> fields = new HashMap<String, Object>();
+
+ public AuditingGenericEvent() {
+ super();
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+ // public Map<String, Object> getFields() {
+ // return fields;
+ // }
+ //
+ // public void setFields(Map<String, Object> fields) {
+ // this.fields = fields;
+ // }
+
+ public void fillFields() {
+
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java
new file mode 100644
index 0000000000..bd8c032390
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java
@@ -0,0 +1,191 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE)
+public class AuditingGetUebClusterEvent extends AuditingGenericEvent {
+ private static String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TEMPLATE = "action=\"%s\" "
+ + " consumerId=\"%s\" statusTime=\"%s\" status=\"%s\" status_desc=\"%s\" ";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column(name = "consumer_id")
+ private String consumerId;
+
+ public AuditingGetUebClusterEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public AuditingGetUebClusterEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ } else {
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID);
+ if (value != null) {
+ setConsumerId((String) value);
+ }
+
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+
+ }
+
+ public String getConsumerId() {
+ return consumerId;
+ }
+
+ public void setConsumerId(String consumerId) {
+ this.consumerId = consumerId;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ @Override
+ public String toString() {
+ return "AuditingGetUebClusterEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1
+ + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action
+ + ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java
new file mode 100644
index 0000000000..01774ca63f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java
@@ -0,0 +1,49 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+public interface AuditingTypesConstants {
+
+ public static final String ARTIFACT_KEYSPACE = "sdcartifact";
+ public static final String AUDIT_KEYSPACE = "sdcaudit";
+ public static final String COMPONENT_KEYSPACE = "sdccomponent";
+ public static final String TITAN_KEYSPACE = "titan";
+
+ public static final String USER_ADMIN_EVENT_TYPE = "useradminevent";
+ public static final String USER_ACCESS_EVENT_TYPE = "useraccessevent";
+ public static final String RESOURCE_ADMIN_EVENT_TYPE = "resourceadminevent";
+ public static final String DISTRIBUTION_DOWNLOAD_EVENT_TYPE = "distributiondownloadevent";
+
+ public static final String DISTRIBUTION_ENGINE_EVENT_TYPE = "distributionengineevent";
+ public static final String DISTRIBUTION_NOTIFICATION_EVENT_TYPE = "distributionnotificationevent";
+ public static final String DISTRIBUTION_STATUS_EVENT_TYPE = "distributionstatusevent";
+ public static final String DISTRIBUTION_DEPLOY_EVENT_TYPE = "distributiondeployevent";
+ public static final String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE = "auditinggetuebclusterevent";
+ public static final String DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE = "auditinggetvalidartifacttypesevent";
+
+ public static final String AUTH_EVENT_TYPE = "authevent";
+ public static final String CONSUMER_EVENT_TYPE = "consumerevent";
+ public static final String CATEGORY_EVENT_TYPE = "categoryevent";
+ public static final String GET_USERS_LIST_EVENT_TYPE = "getuserslistevent";
+ public static final String GET_CATEGORY_HIERARCHY_EVENT_TYPE = "getcategoryhierarchyevent";
+ public static final String EXTERNAL_API_EVENT_TYPE = "externalapievent";
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java
new file mode 100644
index 0000000000..99a42e852e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java
@@ -0,0 +1,209 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = "sdcAudit", name = AuditingTypesConstants.AUTH_EVENT_TYPE)
+public class AuthEvent extends AuditingGenericEvent {
+
+ private static String AUTH_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "URL=\"%s\" USER=\"%s\" AUTH_STATUS=\"%s\" " + "REALM=\"%s\" status=\"%s\" desc=\"%s\"";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column
+ private String url;
+ @Column
+ private String user;
+
+ @Column(name = "auth_status")
+ private String authStatus;
+
+ @Column
+ private String realm;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column(name = "request_id")
+ protected String requestId;
+
+ public AuthEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getUser() {
+ return user;
+ }
+
+ public void setUser(String user) {
+ this.user = user;
+ }
+
+ public String getAuthStatus() {
+ return authStatus;
+ }
+
+ public void setAuthStatus(String authStatus) {
+ this.authStatus = authStatus;
+ }
+
+ public String getRealm() {
+ return realm;
+ }
+
+ public void setRealm(String realm) {
+ this.realm = realm;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public AuthEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_AUTH_URL);
+ if (value != null) {
+ setUrl((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_AUTH_USER);
+ if (value != null) {
+ setUser((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS);
+ if (value != null) {
+ setAuthStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_AUTH_REALM);
+ if (value != null) {
+ setRealm((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_URL.getDisplayName(), getUrl());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_USER.getDisplayName(), getUser());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS.getDisplayName(), getAuthStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_REALM.getDisplayName(), getRealm());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java
new file mode 100644
index 0000000000..a970c84847
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java
@@ -0,0 +1,240 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.CATEGORY_EVENT_TYPE)
+public class CategoryEvent extends AuditingGenericEvent {
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column
+ String action;
+ @Column
+ String status;
+ @Column(name = "description")
+ String desc;
+
+ @Column(name = "category_name")
+ String categoryName;
+
+ @Column(name = "sub_category_name")
+ String subCategoryName;
+
+ @Column(name = "grouping_name")
+ String groupingName;
+
+ @Column
+ String modifier;
+
+ @Column(name = "service_instance_id")
+ String serviceInstanceId;
+
+ @Column(name = "resource_type")
+ String resourceType;
+
+ @Column(name = "request_id")
+ String requestId;
+
+ public CategoryEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public CategoryEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME);
+ if (value != null) {
+ setCategoryName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME);
+ if (value != null) {
+ setSubCategoryName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME);
+ if (value != null) {
+ setGroupingName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE);
+ if (value != null) {
+ setResourceType((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+
+ }
+
+ @Override
+ public void fillFields() {
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME.getDisplayName(), getCategoryName());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME.getDisplayName(), getSubCategoryName());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME.getDisplayName(), getGroupingName());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getCategoryName() {
+ return categoryName;
+ }
+
+ public void setCategoryName(String categoryName) {
+ this.categoryName = categoryName;
+ }
+
+ public String getSubCategoryName() {
+ return subCategoryName;
+ }
+
+ public void setSubCategoryName(String subCategoryName) {
+ this.subCategoryName = subCategoryName;
+ }
+
+ public String getGroupingName() {
+ return groupingName;
+ }
+
+ public void setGroupingName(String groupingName) {
+ this.groupingName = groupingName;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java
new file mode 100644
index 0000000000..6c5bc3140d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java
@@ -0,0 +1,184 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.CONSUMER_EVENT_TYPE)
+public class ConsumerEvent extends AuditingGenericEvent {
+ private static String CONSUMER_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "modifier=\"%s\" ecompUser=\"%s\" status=\"%s\" desc=\"%s\"";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column
+ private String modifier;
+
+ @Column(name = "ecomp_user")
+ private String ecompUser;
+
+ public ConsumerEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public ConsumerEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER);
+ if (value != null) {
+ setEcompUser((String) value);
+ }
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER.getDisplayName(), getEcompUser());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getEcompUser() {
+ return ecompUser;
+ }
+
+ public void setEcompUser(String ecompUser) {
+ this.ecompUser = ecompUser;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ @Override
+ public String toString() {
+ return "ConsumerEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ + requestId + ", action=" + action + ", status=" + status + ", desc=" + desc + ", modifier=" + modifier
+ + ", ecompUser=" + ecompUser + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java
new file mode 100644
index 0000000000..6ee320575c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java
@@ -0,0 +1,253 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE)
+public class DistributionDeployEvent extends AuditingGenericEvent {
+
+ private static String DISTRIBUTION_DEPLOY_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "resourceName=\"%s\" resourceType=\"%s\" currVersion=\"%s\" "
+ + "modifierName=\"%s\" modifierUid=\"%s\" did=\"%s\" " + "status=\"%s\" desc=\"%s\"";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column(name = "resource_name")
+ private String resourceName;
+
+ @Column(name = "resource_type")
+ private String resourceType;
+
+ @Column(name = "curr_version")
+ private String currVersion;
+
+ @Column
+ private String modifier;
+
+ @Column
+ private String did;
+
+ public DistributionDeployEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public DistributionDeployEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID);
+ if (value != null) {
+ setDid((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION);
+ if (value != null) {
+ setCurrVersion((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME);
+ if (value != null) {
+ setResourceName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE);
+ if (value != null) {
+ setResourceType((String) value);
+ }
+
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public String getCurrVersion() {
+ return currVersion;
+ }
+
+ public void setCurrVersion(String currVersion) {
+ this.currVersion = currVersion;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getDid() {
+ return did;
+ }
+
+ public void setDid(String did) {
+ this.did = did;
+ }
+
+ @Override
+ public String toString() {
+ return "DistributionDeployEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status
+ + ", desc=" + desc + ", resourceName=" + resourceName + ", resourceType=" + resourceType
+ + ", currVersion=" + currVersion + ", modifier=" + modifier + ", did=" + did + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java
new file mode 100644
index 0000000000..4b9fc0318f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java
@@ -0,0 +1,205 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_DOWNLOAD_EVENT_TYPE)
+public class DistributionDownloadEvent extends AuditingGenericEvent {
+
+ private static String DISTRIBUTION_DOWNLOAD_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "consumerId=\"%s\" resourceUrl=\"%s\" status=\"%s\" desc=\"%s\"";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column(name = "consumer_id")
+ private String consumerId;
+
+ @Column(name = "resource_url")
+ private String resourceUrl;
+
+ public DistributionDownloadEvent() {
+ super();
+
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public DistributionDownloadEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID);
+ if (value != null) {
+ setConsumerId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL);
+ if (value != null) {
+ setResourceUrl((String) value);
+ }
+
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResourceUrl());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public String getConsumerId() {
+ return consumerId;
+ }
+
+ public void setConsumerId(String consumerId) {
+ this.consumerId = consumerId;
+ }
+
+ public String getResourceUrl() {
+ return resourceUrl;
+ }
+
+ public void setResourceUrl(String resourceUrl) {
+ this.resourceUrl = resourceUrl;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ @Override
+ public String toString() {
+ return "DistributionDownloadEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1
+ + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action
+ + ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + ", resourceUrl="
+ + resourceUrl + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java
new file mode 100644
index 0000000000..b125e7a712
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java
@@ -0,0 +1,273 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE)
+public class DistributionEngineEvent extends AuditingGenericEvent {
+
+ private static String DISTRIBUTION_ENGINE_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "environmentName=\"%s\" topicName=\"%s\" role=\"%s\" apiKey=\"%s\" " + "status=\"%s\" ";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column(name = "consumer_id")
+ private String consumerId;
+
+ @Column(name = "DSTATUS_TOPIC")
+ private String dstatusTopic;
+
+ @Column(name = "DNOTIF_TOPIC")
+ private String dnotifTopic;
+
+ @Column(name = "d_env")
+ private String environmentName;
+
+ @Column
+ private String role;
+
+ @Column(name = "api_key")
+ private String apiKey;
+
+ public DistributionEngineEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public DistributionEngineEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ } else {
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID);
+ if (value != null) {
+ setConsumerId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME);
+ if (value != null) {
+ setDstatusTopic((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME);
+ if (value != null) {
+ setDnotifTopic((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY);
+ if (value != null) {
+ setApiKey((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME);
+ if (value != null) {
+ setEnvironmentName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE);
+ if (value != null) {
+ setRole((String) value);
+ }
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY.getDisplayName(), getApiKey());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME.getDisplayName(), getEnvironmentName());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE.getDisplayName(), getRole());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME.getDisplayName(), getDstatusTopic());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME.getDisplayName(),
+ getDnotifTopic());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public String getDstatusTopic() {
+ return dstatusTopic;
+ }
+
+ public void setDstatusTopic(String dstatusTopic) {
+ this.dstatusTopic = dstatusTopic;
+ }
+
+ public String getDnotifTopic() {
+ return dnotifTopic;
+ }
+
+ public void setDnotifTopic(String dnotifTopic) {
+ this.dnotifTopic = dnotifTopic;
+ }
+
+ public String getEnvironmentName() {
+ return environmentName;
+ }
+
+ public void setEnvironmentName(String environmentName) {
+ this.environmentName = environmentName;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ public String getApiKey() {
+ return apiKey;
+ }
+
+ public void setApiKey(String apiKey) {
+ this.apiKey = apiKey;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getConsumerId() {
+ return consumerId;
+ }
+
+ public void setConsumerId(String consumerId) {
+ this.consumerId = consumerId;
+ }
+
+ @Override
+ public String toString() {
+ return "DistributionEngineEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status
+ + ", desc=" + desc + ", consumerId=" + consumerId + ", dstatusTopic=" + dstatusTopic + ", dnotifTopic="
+ + dnotifTopic + ", environmentName=" + environmentName + ", role=" + role + ", apiKey=" + apiKey + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java
new file mode 100644
index 0000000000..6420f08fb5
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java
@@ -0,0 +1,286 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_NOTIFICATION_EVENT_TYPE)
+public class DistributionNotificationEvent extends AuditingGenericEvent {
+
+ private static String DISTRIBUTION_NOTIFICATION_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "resourceName=\"%s\" resourceType=\"%s\" currVersion=\"%s\" " + "modifierName=\"%s\" modifierUid=\"%s\" "
+ + "currState=\"%s\" distributionId=\"%s\" " + "topicName=\"%s\" status=\"%s\" description=\"%s\"";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column(name = "resource_name")
+ private String resourceName;
+
+ @Column(name = "resource_type")
+ private String resourceType;
+
+ @Column(name = "curr_version")
+ private String currVersion;
+
+ @Column
+ private String modifier;
+
+ @Column(name = "curr_state")
+ private String currState;
+
+ @Column(name = "topic_name")
+ private String topicName;
+
+ @Column
+ private String did;
+
+ public DistributionNotificationEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public DistributionNotificationEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID);
+ if (value != null) {
+ setDid((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE);
+ if (value != null) {
+ setCurrState((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION);
+ if (value != null) {
+ setCurrVersion((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME);
+ if (value != null) {
+ setResourceName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE);
+ if (value != null) {
+ setResourceType((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME);
+ if (value != null) {
+ setTopicName((String) value);
+ }
+
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE.getDisplayName(), getCurrState());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME.getDisplayName(), getTopicName());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public String getCurrVersion() {
+ return currVersion;
+ }
+
+ public void setCurrVersion(String currVersion) {
+ this.currVersion = currVersion;
+ }
+
+ public String getCurrState() {
+ return currState;
+ }
+
+ public void setCurrState(String currState) {
+ this.currState = currState;
+ }
+
+ public String getTopicName() {
+ return topicName;
+ }
+
+ public void setTopicName(String topicName) {
+ this.topicName = topicName;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getDid() {
+ return did;
+ }
+
+ public void setDid(String did) {
+ this.did = did;
+ }
+
+ @Override
+ public String toString() {
+ return "DistributionNotificationEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1
+ + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action
+ + ", status=" + status + ", desc=" + desc + ", resourceName=" + resourceName + ", resourceType="
+ + resourceType + ", currVersion=" + currVersion + ", modifier=" + modifier + ", currState=" + currState
+ + ", topicName=" + topicName + ", did=" + did + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java
new file mode 100644
index 0000000000..6565b824ac
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java
@@ -0,0 +1,254 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_STATUS_EVENT_TYPE)
+public class DistributionStatusEvent extends AuditingGenericEvent {
+
+ private static String DISTRIBUTION_STATUS_NOTIFICATION_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "did=\"%s\" consumerId=\"%s\" topicName=\"%s\" resoureURL=\"%s\" statusTime=\"%s\" status=\"%s\" ";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column
+ private String did;
+
+ @Column(name = "consumer_id")
+ private String consumerId;
+
+ @Column(name = "topic_name")
+ private String topicName;
+
+ @Column(name = "resoure_url")
+ private String resoureURL;
+
+ @Column(name = "status_time")
+ private String statusTime;
+
+ public DistributionStatusEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+
+ }
+
+ public DistributionStatusEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID);
+ if (value != null) {
+ setDid((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID);
+ if (value != null) {
+ setConsumerId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME);
+ if (value != null) {
+ setTopicName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL);
+ if (value != null) {
+ setResoureURL((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME);
+ if (value != null) {
+ setStatusTime((String) value);
+ }
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME.getDisplayName(), getStatusTime());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME.getDisplayName(), getTopicName());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResoureURL());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+
+ }
+
+ public String getDid() {
+ return did;
+ }
+
+ public void setDid(String did) {
+ this.did = did;
+ }
+
+ public String getConsumerId() {
+ return consumerId;
+ }
+
+ public void setConsumerId(String consumerId) {
+ this.consumerId = consumerId;
+ }
+
+ public String getTopicName() {
+ return topicName;
+ }
+
+ public void setTopicName(String topicName) {
+ this.topicName = topicName;
+ }
+
+ public String getResoureURL() {
+ return resoureURL;
+ }
+
+ public void setResoureURL(String resoureURL) {
+ this.resoureURL = resoureURL;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp) {
+ this.timestamp1 = timestamp;
+ }
+
+ public String getStatusTime() {
+ return statusTime;
+ }
+
+ public void setStatusTime(String statusTime) {
+ this.statusTime = statusTime;
+ }
+
+ @Override
+ public String toString() {
+ return "DistributionStatusEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status
+ + ", desc=" + desc + ", did=" + did + ", consumerId=" + consumerId + ", topicName=" + topicName
+ + ", resoureURL=" + resoureURL + ", statusTime=" + statusTime + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java
new file mode 100644
index 0000000000..027c57c5c9
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java
@@ -0,0 +1,279 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)
+public class ExternalApiEvent extends AuditingGenericEvent {
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn()
+ protected Date timestamp1;
+
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column(name = "consumer_id")
+ private String consumerId;
+
+ @Column(name = "resource_url")
+ private String resourceURL;
+
+ @Column(name = "resource_name")
+ private String resourceName;
+
+ @Column(name = "resource_type")
+ private String resourceType;
+
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+
+ @Column(name = "modifier")
+ private String modifier;
+
+ @Column(name = "prev_artifact_uuid")
+ private String prevArtifactUuid;
+
+ @Column(name = "curr_artifact_uuid")
+ private String currArtifactUuid;
+
+ @Column(name = "artifact_data")
+ private String artifactData;
+
+ public ExternalApiEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public ExternalApiEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID);
+ if (value != null) {
+ setConsumerId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL);
+ if (value != null) {
+ setResourceURL((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME);
+ if (value != null) {
+ setResourceName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE);
+ if (value != null) {
+ setResourceType((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID);
+ if (value != null) {
+ setPrevArtifactUuid((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID);
+ if (value != null) {
+ setCurrArtifactUuid((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA);
+ if (value != null) {
+ setArtifactData((String) value);
+ }
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResourceURL());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID.getDisplayName(), getPrevArtifactUuid());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID.getDisplayName(), getCurrArtifactUuid());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA.getDisplayName(), getArtifactData());
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getConsumerId() {
+ return consumerId;
+ }
+
+ public void setConsumerId(String consumerId) {
+ this.consumerId = consumerId;
+ }
+
+ public String getResourceURL() {
+ return resourceURL;
+ }
+
+ public void setResourceURL(String resourceURL) {
+ this.resourceURL = resourceURL;
+ }
+
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getPrevArtifactUuid() {
+ return prevArtifactUuid;
+ }
+
+ public void setPrevArtifactUuid(String prevArtifactUuid) {
+ this.prevArtifactUuid = prevArtifactUuid;
+ }
+
+ public String getCurrArtifactUuid() {
+ return currArtifactUuid;
+ }
+
+ public void setCurrArtifactUuid(String currArtifactUuid) {
+ this.currArtifactUuid = currArtifactUuid;
+ }
+
+ public String getArtifactData() {
+ return artifactData;
+ }
+
+ public void setArtifactData(String artifactData) {
+ this.artifactData = artifactData;
+ }
+
+ @Override
+ public String toString() {
+ return "ExternalApiEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", action=" + action
+ + ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + ", resourceURL="
+ + resourceURL + ", resourceName=" + resourceName + ", resourceType=" + resourceType
+ + ", serviceInstanceId=" + serviceInstanceId + ", modifier=" + modifier + ", prevArtifactUuid="
+ + prevArtifactUuid + ", currArtifactUuid=" + currArtifactUuid + ", artifactData=" + artifactData + "]";
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java
new file mode 100644
index 0000000000..0b86651b8a
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java
@@ -0,0 +1,182 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.GET_CATEGORY_HIERARCHY_EVENT_TYPE)
+public class GetCategoryHierarchyEvent extends AuditingGenericEvent {
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn()
+ // @Column(name="timestamp")
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column
+ private String modifier;
+
+ @Column
+ private String details;
+
+ public GetCategoryHierarchyEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public GetCategoryHierarchyEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DETAILS);
+ if (value != null) {
+ setDetails((String) value);
+ }
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DETAILS.getDisplayName(), getDetails());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getDetails() {
+ return details;
+ }
+
+ public void setDetails(String details) {
+ this.details = details;
+ }
+
+ @Override
+ public String toString() {
+ return "GetCategoryHierarchyEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1
+ + ", requestId=" + requestId + ", action=" + action + ", status=" + status + ", desc=" + desc
+ + ", modifier=" + modifier + ", details=" + details + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java
new file mode 100644
index 0000000000..728a0430b0
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java
@@ -0,0 +1,186 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.GET_USERS_LIST_EVENT_TYPE)
+public class GetUsersListEvent extends AuditingGenericEvent {
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column
+ private String modifier;
+
+ @Column
+ private String details;
+
+ public GetUsersListEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public GetUsersListEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS);
+ if (value != null) {
+ setDetails((String) value);
+ } else {
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DETAILS);
+ if (value != null) {
+ setDetails((String) value);
+ }
+ }
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS.getDisplayName(), getDetails());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getDetails() {
+ return details;
+ }
+
+ public void setDetails(String details) {
+ this.details = details;
+ }
+
+ @Override
+ public String toString() {
+ return "GetUsersListEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ + requestId + ", action=" + action + ", status=" + status + ", desc=" + desc + ", modifier=" + modifier
+ + ", details=" + details + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java
new file mode 100644
index 0000000000..21a84751da
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java
@@ -0,0 +1,437 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE)
+public class ResourceAdminEvent extends AuditingGenericEvent {
+
+ private static String RESOURCE_ADMIN_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "resourceName=\"%s\" resourceType=\"%s\" prevVersion=\"%s\" currVersion=\"%s\" "
+ + "modifierName=\"%s\" modifierUid=\"%s\" " + "prevState=\"%s\" currState=\"%s\" "
+ + "checkinComment=\"%s\" prevArtifactUuid=\"%s\" currArtifactUuid=\"%s\" " + "artifactData=\"%s\" "
+ + "status=\"%s\" desc=\"%s\"";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column
+ protected String action;
+
+ @Column(name = "resource_type")
+ protected String resourceType;
+
+ @Column(name = "prev_version")
+ protected String prevVersion;
+
+ @Column(name = "prev_state")
+ protected String prevState;
+
+ @Column(name = "curr_state")
+ protected String currState;
+
+ @Column(name = "resource_name")
+ private String resourceName;
+
+ @Column(name = "curr_version")
+ private String currVersion;
+
+ @Column(name = "request_id")
+ protected String requestId;
+
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column
+ protected String modifier;
+
+ @Column(name = "prev_artifact_UUID")
+ protected String prevArtifactUUID;
+
+ @Column(name = "curr_artifact_UUID")
+ protected String currArtifactUUID;
+
+ @Column(name = "artifact_data")
+ protected String artifactData;
+
+ @Column
+ protected String did;
+
+ @Column(name = "dprev_status")
+ protected String dprevStatus;
+
+ @Column(name = "dcurr_status")
+ protected String dcurrStatus;
+
+ @Column(name = "tosca_node_type")
+ protected String toscaNodeType;
+
+ @Column
+ protected String comment;
+
+ @Column(name = "invariant_UUID")
+ protected String invariantUUID;
+
+ public ResourceAdminEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public ResourceAdminEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE);
+ if (value != null) {
+ setResourceType((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION);
+ if (value != null) {
+ setPrevVersion((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE);
+ if (value != null) {
+ setPrevState((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME);
+ if (value != null) {
+ setResourceName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION);
+ if (value != null) {
+ setCurrVersion((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE);
+ if (value != null) {
+ setCurrState((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID);
+ if (value != null) {
+ setPrevArtifactUUID((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID);
+ if (value != null) {
+ setCurrArtifactUUID((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA);
+ if (value != null) {
+ setArtifactData((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT);
+ if (value != null) {
+ setComment((String) value);
+ }
+
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS);
+ if (value != null) {
+ setDcurrStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS);
+ if (value != null) {
+ setDprevStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID);
+ if (value != null) {
+ setDid((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE);
+ if (value != null) {
+ setToscaNodeType((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID);
+ if (value != null) {
+ setInvariantUUID((String) value);
+ }
+
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION.getDisplayName(), getPrevVersion());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE.getDisplayName(), getPrevState());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE.getDisplayName(), getCurrState());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID.getDisplayName(), getPrevArtifactUUID());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID.getDisplayName(), getCurrArtifactUUID());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA.getDisplayName(), getArtifactData());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT.getDisplayName(), getComment());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS.getDisplayName(), getDcurrStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS.getDisplayName(), getDprevStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE.getDisplayName(), getToscaNodeType());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID.getDisplayName(), getInvariantUUID());
+
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public String getPrevVersion() {
+ return prevVersion;
+ }
+
+ public void setPrevVersion(String prevVersion) {
+ this.prevVersion = prevVersion;
+ }
+
+ public String getCurrVersion() {
+ return currVersion;
+ }
+
+ public void setCurrVersion(String currVersion) {
+ this.currVersion = currVersion;
+ }
+
+ public String getPrevState() {
+ return prevState;
+ }
+
+ public void setPrevState(String prevState) {
+ this.prevState = prevState;
+ }
+
+ public String getCurrState() {
+ return currState;
+ }
+
+ public void setCurrState(String currState) {
+ this.currState = currState;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getPrevArtifactUUID() {
+ return prevArtifactUUID;
+ }
+
+ public void setPrevArtifactUUID(String prevArtifactUUID) {
+ this.prevArtifactUUID = prevArtifactUUID;
+ }
+
+ public String getCurrArtifactUUID() {
+ return currArtifactUUID;
+ }
+
+ public void setCurrArtifactUUID(String currArtifactUUID) {
+ this.currArtifactUUID = currArtifactUUID;
+ }
+
+ public String getArtifactData() {
+ return artifactData;
+ }
+
+ public void setArtifactData(String artifactData) {
+ this.artifactData = artifactData;
+ }
+
+ public String getDid() {
+ return did;
+ }
+
+ public void setDid(String did) {
+ this.did = did;
+ }
+
+ public String getDprevStatus() {
+ return dprevStatus;
+ }
+
+ public void setDprevStatus(String dprevStatus) {
+ this.dprevStatus = dprevStatus;
+ }
+
+ public String getDcurrStatus() {
+ return dcurrStatus;
+ }
+
+ public void setDcurrStatus(String dcurrStatus) {
+ this.dcurrStatus = dcurrStatus;
+ }
+
+ public String getToscaNodeType() {
+ return toscaNodeType;
+ }
+
+ public void setToscaNodeType(String toscaNodeType) {
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ public String getComment() {
+ return comment;
+ }
+
+ public void setComment(String comment) {
+ this.comment = comment;
+ }
+
+ public String getInvariantUUID() {
+ return invariantUUID;
+ }
+
+ public void setInvariantUUID(String invariantUUID) {
+ this.invariantUUID = invariantUUID;
+ }
+
+ @Override
+ public String toString() {
+ return "ResourceAdminEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", action="
+ + action + ", resourceType=" + resourceType + ", prevVersion=" + prevVersion + ", prevState="
+ + prevState + ", currState=" + currState + ", resourceName=" + resourceName + ", currVersion="
+ + currVersion + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", status="
+ + status + ", desc=" + desc + ", modifier=" + modifier + ", prevArtifactUUID=" + prevArtifactUUID
+ + ", currArtifactUUID=" + currArtifactUUID + ", artifactData=" + artifactData + ", invariantUUID="
+ + invariantUUID + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java
new file mode 100644
index 0000000000..a1ae1e2df1
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java
@@ -0,0 +1,179 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.USER_ACCESS_EVENT_TYPE)
+public class UserAccessEvent extends AuditingGenericEvent {
+ private static String USER_ACCESS_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "userUid=\"%s\" userName=\"%s\" status=\"%s\" desc=\"%s\"";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "REQUEST_ID")
+ protected String requestId;
+
+ @Column(name = "USER")
+ private String userUid;
+
+ @Column
+ private String status;
+
+ @Column(name = "DESCRIPTION")
+ private String desc;
+
+ @Column
+ private String action;
+
+ @Column(name = "service_instance_id")
+ private String serviceInstanceId;
+
+ public UserAccessEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public UserAccessEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID);
+ if (value != null) {
+ setUserUid((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID.getDisplayName(), getUserUid());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public String getUserUid() {
+ return userUid;
+ }
+
+ public void setUserUid(String userUid) {
+ this.userUid = userUid;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp) {
+ this.timestamp1 = timestamp;
+ }
+
+ @Override
+ public String toString() {
+ return "UserAccessEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ + requestId + ", userUid=" + userUid + ", status=" + status + ", desc=" + desc + ", action=" + action
+ + ", serviceInstanceId=" + serviceInstanceId + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java
new file mode 100644
index 0000000000..72d7d2ff6d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java
@@ -0,0 +1,224 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.EnumMap;
+import java.util.TimeZone;
+import java.util.UUID;
+
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.utils.UUIDs;
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.USER_ADMIN_EVENT_TYPE)
+public class UserAdminEvent extends AuditingGenericEvent {
+
+ private static String USER_ADMIN_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" modifierName=\"%s\" modifierUid=\"%s\" "
+ + "userUid=\"%s\" userName=\"%s\" userEmail=\"%s\" userRole=\"%s\" "
+ + "userBeforeUid=\"%s\" userBeforeName=\"%s\" userBeforeEmail=\"%s\" userBeforeRole=\"%s\" "
+ + "userAfterUid=\"%s\" userAfterName=\"%s\" userAfterEmail=\"%s\" userAfterRole=\"%s\" "
+ + "status=\"%s\" desc=\"%s\"";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "REQUEST_ID")
+ protected String requestId;
+
+ @Column(name = "SERVICE_INSTANCE_ID")
+ protected String serviceInstanceId;
+
+ @Column(name = "ACTION")
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column
+ private String modifier;
+
+ @Column(name = "user_before")
+ private String userBefore;
+
+ @Column(name = "user_after")
+ private String userAfter;
+
+ public UserAdminEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+
+ }
+
+ public UserAdminEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE);
+ if (value != null) {
+ setUserBefore((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_AFTER);
+ if (value != null) {
+ setUserAfter((String) value);
+ }
+
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE.getDisplayName(), getUserBefore());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER.getDisplayName(), getUserAfter());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getUserBefore() {
+ return userBefore;
+ }
+
+ public void setUserBefore(String userBeforeName) {
+ this.userBefore = userBeforeName;
+ }
+
+ public String getUserAfter() {
+ return userAfter;
+ }
+
+ public void setUserAfter(String userAfterName) {
+ this.userAfter = userAfterName;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp) {
+ this.timestamp1 = timestamp;
+ }
+
+ @Override
+ public String toString() {
+ return "UserAdminEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status
+ + ", desc=" + desc + ", modifierUid=" + modifier + ", userBefore=" + userBefore + ", userAfter="
+ + userAfter + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java
new file mode 100644
index 0000000000..d42eb78ed3
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.category;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.category.CategoryDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class CategoryData extends GraphNode {
+ private CategoryDataDefinition categoryDataDefinition;
+
+ public CategoryData(NodeTypeEnum label) {
+ super(label);
+ categoryDataDefinition = new CategoryDataDefinition();
+ }
+
+ public CategoryData(NodeTypeEnum label, CategoryDataDefinition categoryDataDefinition) {
+ super(label);
+ this.categoryDataDefinition = categoryDataDefinition;
+ }
+
+ public CategoryData(Map<String, Object> properties) {
+ this(NodeTypeEnum.getByName((String) properties.get(GraphPropertiesDictionary.LABEL.getProperty())));
+
+ categoryDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ categoryDataDefinition
+ .setNormalizedName((String) properties.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()));
+ categoryDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+
+ Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> iconsfromJson = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.ICONS.getProperty()), listType);
+ categoryDataDefinition.setIcons(iconsfromJson);
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return categoryDataDefinition.getUniqueId();
+ }
+
+ public CategoryDataDefinition getCategoryDataDefinition() {
+ return categoryDataDefinition;
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, categoryDataDefinition.getUniqueId());
+ addIfExists(map, GraphPropertiesDictionary.NAME, categoryDataDefinition.getName());
+ addIfExists(map, GraphPropertiesDictionary.NORMALIZED_NAME, categoryDataDefinition.getNormalizedName());
+ // String icons=getGson().toJson(categoryDataDefinition.getIcons());
+ // addIfExists(map, GraphPropertiesDictionary.ICONS, icons);
+ addIfExists(map, GraphPropertiesDictionary.ICONS, categoryDataDefinition.getIcons());
+ return map;
+ }
+
+ @Override
+ public String toString() {
+ return "CategoryData [categoryDataDefinition=" + categoryDataDefinition + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java
new file mode 100644
index 0000000000..ca40ae986b
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java
@@ -0,0 +1,73 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.category;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.category.GroupingDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public class GroupingData extends GraphNode {
+
+ private GroupingDataDefinition groupingDataDefinition;
+
+ public GroupingData(NodeTypeEnum label) {
+ super(label);
+ groupingDataDefinition = new GroupingDataDefinition();
+ }
+
+ public GroupingData(NodeTypeEnum label, GroupingDataDefinition groupingDataDefinition) {
+ super(label);
+ this.groupingDataDefinition = groupingDataDefinition;
+ }
+
+ public GroupingData(Map<String, Object> properties) {
+ this(NodeTypeEnum.getByName((String) properties.get(GraphPropertiesDictionary.LABEL.getProperty())));
+
+ groupingDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ groupingDataDefinition
+ .setNormalizedName((String) properties.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()));
+ groupingDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+ }
+
+ public GroupingDataDefinition getGroupingDataDefinition() {
+ return groupingDataDefinition;
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return groupingDataDefinition.getUniqueId();
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, groupingDataDefinition.getUniqueId());
+ addIfExists(map, GraphPropertiesDictionary.NAME, groupingDataDefinition.getName());
+ addIfExists(map, GraphPropertiesDictionary.NORMALIZED_NAME, groupingDataDefinition.getNormalizedName());
+ return map;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java
new file mode 100644
index 0000000000..1112b4514d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java
@@ -0,0 +1,86 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.data.category;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.category.SubCategoryDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+import com.google.gson.reflect.TypeToken;
+
+public class SubCategoryData extends GraphNode {
+
+ private SubCategoryDataDefinition subCategoryDataDefinition;
+
+ public SubCategoryData(NodeTypeEnum label) {
+ super(label);
+ subCategoryDataDefinition = new SubCategoryDataDefinition();
+ }
+
+ public SubCategoryData(NodeTypeEnum label, SubCategoryDataDefinition subCategoryDataDefinition) {
+ super(label);
+ this.subCategoryDataDefinition = subCategoryDataDefinition;
+ }
+
+ public SubCategoryData(Map<String, Object> properties) {
+ this(NodeTypeEnum.getByName((String) properties.get(GraphPropertiesDictionary.LABEL.getProperty())));
+
+ subCategoryDataDefinition
+ .setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ subCategoryDataDefinition
+ .setNormalizedName((String) properties.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()));
+ subCategoryDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty()));
+
+ Type listType = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> iconsfromJson = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.ICONS.getProperty()), listType);
+ subCategoryDataDefinition.setIcons(iconsfromJson);
+ }
+
+ public SubCategoryDataDefinition getSubCategoryDataDefinition() {
+ return subCategoryDataDefinition;
+ }
+
+ @Override
+ public Object getUniqueId() {
+ return subCategoryDataDefinition.getUniqueId();
+ }
+
+ @Override
+ public Map<String, Object> toGraphMap() {
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, subCategoryDataDefinition.getUniqueId());
+ addIfExists(map, GraphPropertiesDictionary.NAME, subCategoryDataDefinition.getName());
+ addIfExists(map, GraphPropertiesDictionary.NORMALIZED_NAME, subCategoryDataDefinition.getNormalizedName());
+ // String icons=getGson().toJson(subCategoryDataDefinition.getIcons());
+ // addIfExists(map, GraphPropertiesDictionary.ICONS, icons);
+ addIfExists(map, GraphPropertiesDictionary.ICONS, subCategoryDataDefinition.getIcons());
+ return map;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/DeleteDeployedException.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/DeleteDeployedException.java
new file mode 100644
index 0000000000..f0d320114f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/DeleteDeployedException.java
@@ -0,0 +1,42 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.exception;
+
+import org.openecomp.sdc.exception.TechnicalException;
+
+/**
+ * Thrown when a deployed environment / topology is about to be deleted
+ *
+ * @author mourouvi
+ *
+ */
+public class DeleteDeployedException extends TechnicalException {
+
+ private static final long serialVersionUID = -5192834855057177252L;
+
+ public DeleteDeployedException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public DeleteDeployedException(String message) {
+ super(message);
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/InitializationException.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/InitializationException.java
new file mode 100644
index 0000000000..9c4337554e
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/InitializationException.java
@@ -0,0 +1,32 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.exception;
+
+import org.openecomp.sdc.exception.TechnicalException;
+
+/**
+ * Exception to be thrown in case of an error that prevents alien to startup.
+ */
+public class InitializationException extends TechnicalException {
+ public InitializationException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/ResourceDAOException.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/ResourceDAOException.java
new file mode 100644
index 0000000000..cae5c47699
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/exception/ResourceDAOException.java
@@ -0,0 +1,58 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.exception;
+
+import org.openecomp.sdc.be.dao.api.ResourceUploadStatus;
+import org.openecomp.sdc.exception.TechnicalException;
+
+public class ResourceDAOException extends TechnicalException {
+
+ private static final long serialVersionUID = 171917520842336653L;
+
+ private ResourceUploadStatus status;
+
+ public ResourceDAOException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public ResourceDAOException(String message) {
+ super(message);
+ }
+
+ public ResourceDAOException(ResourceUploadStatus status, String message, Throwable cause) {
+ super(message, cause);
+ this.status = status;
+ }
+
+ public ResourceDAOException(ResourceUploadStatus status, String message) {
+ super(message);
+ this.status = status;
+ }
+
+ public ResourceUploadStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(ResourceUploadStatus status) {
+ this.status = status;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java
new file mode 100644
index 0000000000..1570ff1ed1
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java
@@ -0,0 +1,206 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources.impl;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ICatalogDAO;
+import org.openecomp.sdc.be.dao.api.ResourceUploadStatus;
+import org.openecomp.sdc.be.resources.api.IResourceUploader;
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.be.resources.exception.ResourceDAOException;
+import org.openecomp.sdc.common.config.EcompErrorName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import fj.data.Either;
+
+@Component("resource-upload")
+public class ResourceUploader implements IResourceUploader {
+
+ private static final String DEFAULT_ARTIFACT_INDEX_NAME = "resources";
+
+ @Resource
+ private ICatalogDAO resourceDAO;
+ private static Logger log = LoggerFactory.getLogger(ResourceUploader.class.getName());
+
+ @PostConstruct
+ public void init() {
+ ConfigurationManager configMgr = ConfigurationManager.getConfigurationManager();
+ String artifactsIndex = null;
+ artifactsIndex = configMgr.getConfiguration().getArtifactsIndex();
+ if (artifactsIndex == null || artifactsIndex.isEmpty()) {
+ artifactsIndex = DEFAULT_ARTIFACT_INDEX_NAME;
+ }
+ resourceDAO.addToIndicesMap(ESArtifactData.class.getSimpleName().toLowerCase(), artifactsIndex);
+ }
+
+ public ResourceUploader() {
+ super();
+ }
+
+ public ResourceUploader(ICatalogDAO resourcetDAO) {
+ super();
+ this.resourceDAO = resourcetDAO;
+ }
+
+ public ICatalogDAO getResourceDAO() {
+ return resourceDAO;
+ }
+
+ public void setResourceDAO(ICatalogDAO resourceDAO) {
+ this.resourceDAO = resourceDAO;
+ }
+
+ @Override
+ public ResourceUploadStatus saveArtifact(ESArtifactData artifactData, boolean isReload) {
+ ResourceUploadStatus status = ResourceUploadStatus.OK;
+ if (resourceDAO == null) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInitializationError,
+ "Save Artifact - internal object not initialized");
+ BeEcompErrorManager.getInstance()
+ .logBeInitializationError("Save Artifact - internal object not initialized");
+ log.debug("update artifact failed - resourceDAO is null");
+ return ResourceUploadStatus.ERROR;
+ }
+
+ Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = getArtifact(artifactData.getId());
+ if (getArtifactStatus.isLeft()) {
+ status = ResourceUploadStatus.ALREADY_EXIST;
+ log.debug("ResourceUploadStatus:saveArtifact artifact with id {} already exist.", artifactData.getId());
+ if (isReload) {
+ status = updateArtifact(artifactData, getArtifactStatus.left().value());
+ }
+ } else {
+ try {
+
+ resourceDAO.writeArtifact(artifactData);
+ status = ResourceUploadStatus.OK;
+
+ } catch (ResourceDAOException e) {
+ status = ResourceUploadStatus.ERROR;
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
+ "Save Artifact to database");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Save Artifact to database");
+ log.debug("ResourceUploadStatus:saveArtifact failed with exception ", e);
+ }
+
+ }
+
+ return status;
+ }
+
+ @Override
+ public ResourceUploadStatus updateArtifact(ESArtifactData artifactUpdateData) {
+ ResourceUploadStatus status = ResourceUploadStatus.OK;
+ if (resourceDAO == null)
+ return ResourceUploadStatus.ERROR;
+
+ Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = getArtifact(artifactUpdateData.getId());
+ if (getArtifactStatus.isRight()) {
+ status = getArtifactStatus.right().value();
+ log.debug("ResourceUploadStatus:updateArtifactt artifact with id {}", artifactUpdateData.getId()
+ + " not exist.");
+ }
+ if (getArtifactStatus.isLeft()) {
+ status = updateArtifact(artifactUpdateData, getArtifactStatus.left().value());
+ }
+
+ return status;
+ }
+
+ /*
+ * @Override public ResourceUploadStatus
+ * updateServiceArtifact(ServiceArtifactData artifactUpdateData) {
+ * ResourceUploadStatus status = ResourceUploadStatus.OK; if(resourceDAO ==
+ * null) return ResourceUploadStatus.ERROR; Either<ServiceArtifactData,
+ * ResourceUploadStatus> getServiceArtifactStatus =
+ * getServiceArtifact(artifactUpdateData.getId());
+ *
+ * if(getServiceArtifactStatus.isRight()){
+ * log.debug("ResourceUploadStatus:updateArtifactt artifact with id {} not exist.",
+ * artifactUpdateData.getId()); status =
+ * getServiceArtifactStatus.right().value(); }
+ * if(getServiceArtifactStatus.isLeft()){ status =
+ * updateServiceArtifact(artifactUpdateData,
+ * getServiceArtifactStatus.left().value()); }
+ *
+ * return status; }
+ *
+ */
+
+ @Override
+ public Either<ESArtifactData, ResourceUploadStatus> getArtifact(String id) {
+ if (resourceDAO == null)
+ return Either.right(ResourceUploadStatus.ERROR);
+
+ return resourceDAO.getArtifact(id);
+ }
+
+ /*
+ * @Override public Either<ServiceArtifactData, ResourceUploadStatus>
+ * getServiceArtifact(String id) { if(resourceDAO == null) return
+ * Either.right(ResourceUploadStatus.ERROR);
+ *
+ * return resourceDAO.getServiceArtifact(id); }
+ */
+ @Override
+ public void deleteArtifact(String id) {
+ if (resourceDAO != null) {
+ resourceDAO.deleteArtifact(id);
+ }
+
+ }
+
+ private ResourceUploadStatus updateArtifact(ESArtifactData artifactUpdateData, ESArtifactData existData) {
+ ResourceUploadStatus status;
+
+ updateData(artifactUpdateData, existData);
+
+ try {
+ resourceDAO.writeArtifact(artifactUpdateData);
+ status = ResourceUploadStatus.OK;
+
+ } catch (ResourceDAOException e) {
+ status = ResourceUploadStatus.ERROR;
+ log.debug("ResourceUploadStatus:updateArtifact failed with exception ", e);
+ }
+ return status;
+ }
+
+ private void updateData(ESArtifactData artifactUpdateData, ESArtifactData existData) {
+
+ if (artifactUpdateData.getData() == null) {
+ artifactUpdateData.setData(existData.getData());
+ }
+
+ }
+
+ @Override
+ public void deleteAllArtifacts() {
+ resourceDAO.deleteAllArtifacts();
+ }
+
+}
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java
new file mode 100644
index 0000000000..aa9d30cb12
--- /dev/null
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java
@@ -0,0 +1,577 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import javax.annotation.Resource;
+
+import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
+import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.IGenericSearchDAO;
+import org.openecomp.sdc.be.dao.api.ResourceUploadStatus;
+import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
+import org.openecomp.sdc.be.resources.api.IResourceUploader;
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestExecutionListeners;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
+import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
+import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
+
+import fj.data.Either;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:application-context-test.xml")
+@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class,
+ DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class }) // ,
+ // CassandraUnitTestExecutionListener.class})
+// @EmbeddedCassandra(host ="localhost", port=9042)
+public class ArtifactDaoTest {
+ private static final String TEST_IMAGES_DIRECTORY = "src/test/resources/images";
+
+ @Resource
+ ElasticSearchClient esclient;
+
+ /*
+ * @Resource(name = "artifact-dao") private IArtifactDAO artifactDAO;
+ */
+
+ @Resource(name = "resource-upload")
+ private IResourceUploader daoUploader;
+ ESArtifactData arData;
+
+ @Resource(name = "resource-dao")
+ private IGenericSearchDAO resourceDAO;
+
+ private String nodeType = "NodeType1";
+ private String nodeTypeVersion = "1.0.0";
+
+ private String nodeType2 = "NodeType2";
+ private String nodeTypeVersion2 = "1.0.1";
+
+ private String nodeType3 = "NodeType3";
+ private String nodeNypeVersion3 = "1.1.1";
+
+ private String topologyId = "topology";
+ private String topologyTemplateName = "topologyTemplate";
+ private String topologyTemplateVersion = "1.1.1";
+
+ private String nodeTypeTemplate1 = "NodeTypeTemplate1";
+ private String nodeTypeTemplate2 = "NodeTypeTemplate2";
+ private String nodeTypeTemplate3 = "NodeTypeTemplate3";
+
+ private static ConfigurationManager configurationManager;
+
+ @Before
+ public void before() {
+ // try {
+ // clearIndex(ICatalogDAO.RESOURCES_INDEX, ArtifactData.class);
+ // clearIndex(ICatalogDAO.RESOURCES_INDEX, ServiceArtifactData.class);
+ // } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // }
+
+ }
+
+ @BeforeClass
+ public static void setupBeforeClass() {
+ ExternalConfiguration.setAppName("catalog-dao");
+ String appConfigDir = "src/test/resources/config/catalog-dao";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
+ appConfigDir);
+ configurationManager = new ConfigurationManager(configurationSource);
+ }
+
+ // @Before
+ // public void createSchema(){
+ // SdcSchemaBuilder.createSchema();
+ // }
+ //
+
+ @Test
+ public void testSaveNewArtifact() {
+ // daoUploader = new ArtifactUploader(artifactDAO);
+ if (daoUploader == null) {
+ assertTrue(false);
+ }
+ String strData = "qweqwqweqw34e4wrwer";
+
+ String myNodeType = "MyNewNodeType";
+
+ ESArtifactData arData = new ESArtifactData("artifactNewMarina11", strData.getBytes());
+
+ ResourceUploadStatus status = daoUploader.saveArtifact(arData, true);
+
+ assertEquals(status, ResourceUploadStatus.OK);
+
+ daoUploader.deleteArtifact(arData.getId());
+
+ }
+
+ /*
+ * @Test public void testSaveNewImage(){
+ *
+ * Path iconPath = Paths.get(TEST_IMAGES_DIRECTORY, "apache.png");
+ *
+ * ImageData imageData = new ImageData(); try {
+ * imageData.setData(Files.readAllBytes(iconPath));
+ * imageData.setComponentName("ComponentMarina");
+ * imageData.setComponentVersion("v.1.0");
+ * imageData.setArtifactName("apache.png");
+ * imageData.setResourceCreator("Marina");
+ * imageData.setResourceLastUpdater("Marina"); ResourceUploadStatus status =
+ * daoUploader.saveImage(imageData, true); assertEquals(status,
+ * ResourceUploadStatus.OK); } catch (IOException e) { // TODO
+ * Auto-generated catch block e.printStackTrace(); }
+ *
+ *
+ * }
+ */
+
+ // @Test
+ // public void testGetArtifactsList() {
+ // //daoUploader = new ArtifactUploader(artifactDAO);
+ // if(daoUploader==null){
+ // assertTrue(false);
+ // }
+ // String myNodeType = "MyListNodeType";
+ //
+ //
+ //
+ // //resourceDAO.save(indexedNodeType);
+ //
+ // String strData = "qweqwqweqw34e4wrwer";
+ // ESArtifactData arData1 = new ESArtifactData("artifactNewMarina_1",
+ // strData.getBytes());
+ //
+ //
+ // ResourceUploadStatus status = daoUploader.saveArtifact(arData1, true);
+ // assertEquals(status, ResourceUploadStatus.OK);
+ //
+ // ESArtifactData arData2 = new ESArtifactData("artifactNewMarina_2",
+ // strData.getBytes());
+ //
+ //
+ // status = daoUploader.saveArtifact(arData2, true);
+ // assertEquals(status, ResourceUploadStatus.OK);
+ //
+ // ESArtifactData arData3 = new ESArtifactData("artifactNewMarina_3",
+ // strData.getBytes());
+ //
+ //
+ // status = daoUploader.saveArtifact(arData3, true);
+ // assertEquals(status, ResourceUploadStatus.OK);
+ //
+ //
+ //
+ // Either<List<ESArtifactData>, ResourceUploadStatus> arrArray =
+ // daoUploader.getArtifacts(myNodeType, nodeTypeVersion);
+ // assertTrue(arrArray.isLeft());
+ //
+ // assertEquals(3, arrArray.left().value().size());
+ //
+ // daoUploader.deleteArtifact(arData1.getId());
+ // daoUploader.deleteArtifact(arData2.getId());
+ // daoUploader.deleteArtifact(arData3.getId());
+ //
+ // //resourceDAO.delete(IndexedNodeType.class, indexedNodeType.getId());
+ //
+ // }
+ //
+
+ /*
+ * @Test public void testGetSeviceArtifactsList() {
+ *
+ * if(daoUploader==null){ assertTrue(false); } String strData =
+ * "qweqwqweqw34e4wrwer";
+ *
+ * ServiceArtifactData serviceArData = new
+ * ServiceArtifactData("serviceArData", topologyTemplateName,
+ * topologyTemplateVersion, nodeTypeTemplate1, nodeType, nodeTypeVersion,
+ * "YANG", strData.getBytes(), strData.getBytes(), "Marina", null);
+ * //serviceArData.setRefArtifactId(arData.getId()); ResourceUploadStatus
+ * status = daoUploader.saveServiceArtifact(serviceArData, true);
+ *
+ * ServiceArtifactData serviceArData1 = new
+ * ServiceArtifactData("serviceArData1", topologyTemplateName,
+ * topologyTemplateVersion, nodeTypeTemplate2, nodeType2, nodeTypeVersion2,
+ * "YANG", strData.getBytes(), strData.getBytes(), "Marina", null);
+ * //serviceArData1.setRefArtifactId(arData4.getId()); status =
+ * daoUploader.saveServiceArtifact(serviceArData1, true);
+ * ServiceArtifactData getServiceData =
+ * daoUploader.getServiceArtifact(serviceArData.getId()).left().value();
+ *
+ * List<ServiceArtifactData> arrArray =
+ * daoUploader.getServiceArtifacts(topologyTemplateName,
+ * topologyTemplateVersion).left().value();
+ *
+ * assertEquals(2, arrArray.size());
+ *
+ * daoUploader.deleteArtifact(serviceArData.getId());
+ * daoUploader.deleteArtifact(serviceArData1.getId());
+ *
+ *
+ * }
+ */
+
+ @Test
+ public void testGetArtifact() {
+
+ String myNodeType = "MyNodeType";
+
+ // resourceDAO.save(indexedNodeType);
+ ESArtifactData arData = getArtifactData(myNodeType, nodeTypeVersion);
+
+ ESArtifactData getData = null;
+ Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = daoUploader
+ .getArtifact(myNodeType + "- dassasd" + ":" + nodeTypeVersion + ":updatedArtifact");
+ if (getArtifactStatus.isRight()) {
+ daoUploader.saveArtifact(arData, true);
+ getArtifactStatus = daoUploader.getArtifact(arData.getId());
+ }
+ assertNotNull(getArtifactStatus.left().value());
+
+ }
+
+ /*
+ * @Test public void testGetSeviceArtifact() {
+ *
+ * ServiceArtifactData servArData = getServiceArtifactData();
+ *
+ * Either<ServiceArtifactData, ResourceUploadStatus>
+ * getServiceArtifactStatus =
+ * daoUploader.getServiceArtifact("MyService:v.1.1:updatedServiceArtifact");
+ * if (!getServiceArtifactStatus.isLeft()){
+ * daoUploader.saveServiceArtifact(servArData, true);
+ * getServiceArtifactStatus =
+ * daoUploader.getServiceArtifact(servArData.getId()); }
+ *
+ * assertNotNull(getServiceArtifactStatus.left().value());
+ *
+ * daoUploader.deleteArtifact(getServiceArtifactStatus.left().value().getId(
+ * ));
+ *
+ *
+ * }
+ */
+
+ /*
+ * @Test public void testGetSeviceArtifactsCollection() {
+ *
+ * prepareTopolgyService(); prepareTestTopolgyService();
+ * Either<ServiceArtifactsDataCollection, ResourceUploadStatus>
+ * getServiceArtifactsCollectionStatus =
+ * daoUploader.getServiceArtifactsCollection(topologyTemplateName,
+ * topologyTemplateVersion); ServiceArtifactsDataCollection serviceAtrifacts
+ * = getServiceArtifactsCollectionStatus.left().value();
+ *
+ * Map<String, List<ArtifactData>> map =
+ * serviceAtrifacts.getServiceArtifactDataMap();
+ *
+ * List<ArtifactData> list = map.get(nodeType); assertNotNull(list);
+ * assertEquals(2, list.size());
+ *
+ *
+ * list = map.get(nodeTypeTemplate1 ); assertNotNull(list); assertEquals(1,
+ * list.size());
+ *
+ * list = map.get(nodeTypeTemplate2 ); assertNotNull(list); assertEquals(1,
+ * list.size());
+ *
+ *
+ * }
+ */
+
+ @Test
+ public void testUpdateArtifact() {
+ // daoUploader = new ArtifactUploader(artifactDAO);
+ if (daoUploader == null) {
+ assertTrue(false);
+ }
+ ResourceUploadStatus status = ResourceUploadStatus.OK;
+
+ String myNodeType = "MyUpdatedNodeType";
+
+ // resourceDAO.save(indexedNodeType);
+
+ ESArtifactData arData = getArtifactData(myNodeType, nodeTypeVersion);
+ Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = daoUploader.getArtifact(arData.getId());
+
+ if (!getArtifactStatus.isLeft())
+ status = daoUploader.saveArtifact(arData, false);
+
+ String payload1 = "new payloadjfdsgh";
+ arData.setDataAsArray(payload1.getBytes());
+
+ status = daoUploader.updateArtifact(arData);
+
+ assertEquals(status, ResourceUploadStatus.OK);
+ // resourceDAO.delete(IndexedNodeType.class, indexedNodeType.getId());
+
+ }
+
+ private ESArtifactData getArtifactData(String componentName, String componentVersion) {
+ String strData = "qweqwqweqw34e4wrwer";
+ ESArtifactData arData = new ESArtifactData("updatedArtifact", strData.getBytes());
+
+ return arData;
+ }
+
+ /*
+ * private ServiceArtifactData getServiceArtifactData(){ String strData =
+ * "qweqwqweqw34e4wrwer"; ServiceArtifactData arData = new
+ * ServiceArtifactData("updatedServiceArtifact", "MyService", "v.1.1",
+ * "MyComponentTemplate", "MyComponent", "v.1.1", "YANG",
+ * strData.getBytes(), strData.getBytes(), "Marina", null);
+ *
+ * return arData; }
+ */
+
+ /*
+ * private void prepareTopolgyService(){
+ *
+ * List<String> listCap = new ArrayList<String>(); listCap.add("very_evil");
+ * List<String> listCap1 = new ArrayList<String>(); listCap.add("evil");
+ * try{ // Initialize test data IndexedNodeType indexedNodeType = new
+ * IndexedNodeType(); CSARDependency dep = new CSARDependency();
+ * dep.setName(nodeType); dep.setVersion(nodeTypeVersion);
+ * indexedNodeType.setElementId(nodeType);
+ * indexedNodeType.setArchiveName(nodeType);
+ * indexedNodeType.setArchiveVersion(nodeTypeVersion);
+ * indexedNodeType.setCreationDate(new Date());
+ * indexedNodeType.setLastUpdateDate(new Date());
+ * indexedNodeType.setDefaultCapabilities(listCap);
+ * resourceDAO.save(indexedNodeType);
+ *
+ *
+ * IndexedNodeType indexedNodeType1 = new IndexedNodeType();
+ * indexedNodeType1.setElementId(nodeType2);
+ * indexedNodeType1.setArchiveName(nodeType2);
+ * indexedNodeType1.setArchiveVersion(nodeTypeVersion2); CSARDependency dep1
+ * = new CSARDependency(); dep1.setName(nodeType2);
+ * dep1.setVersion(nodeTypeVersion2); indexedNodeType1.setCreationDate(new
+ * Date()); indexedNodeType1.setLastUpdateDate(new Date());
+ * indexedNodeType1.setDefaultCapabilities(listCap1);
+ * resourceDAO.save(indexedNodeType1);
+ *
+ *
+ * indexedNodeType.setElementId(nodeType3);
+ * indexedNodeType.setArchiveName(nodeType3);
+ * indexedNodeType.setArchiveVersion(nodeNypeVersion3); CSARDependency dep2
+ * = new CSARDependency(); dep2.setName(nodeType3);
+ * dep2.setVersion(nodeNypeVersion3); indexedNodeType.setCreationDate(new
+ * Date()); indexedNodeType.setLastUpdateDate(new Date());
+ * indexedNodeType.setDefaultCapabilities(null);
+ * resourceDAO.save(indexedNodeType); String osgiliath100Id =
+ * indexedNodeType.getId();
+ *
+ * Topology topology = new Topology(); topology.setId(topologyId);
+ * Set<CSARDependency> dependencies = new HashSet<CSARDependency>();
+ * dependencies.add(dep); dependencies.add(dep2); dependencies.add(dep1);
+ * topology.setDependencies(dependencies); Map<String, NodeTemplate>
+ * nodeTemplates = new HashMap <String, NodeTemplate>();
+ *
+ * NodeTemplate template1 = new NodeTemplate(nodeType, null, null, null,
+ * null, null, null); template1.setName(nodeTypeTemplate1);
+ * nodeTemplates.put(nodeTypeTemplate1, template1 );
+ *
+ * NodeTemplate template2 = new NodeTemplate(nodeType2, null, null, null,
+ * null, null, null); template2.setName(nodeTypeTemplate2 );
+ * nodeTemplates.put(nodeTypeTemplate2, template2 );
+ *
+ * NodeTemplate template3 = new NodeTemplate(nodeType, null, null, null,
+ * null, null, null); template3.setName(nodeTypeTemplate3 );
+ * nodeTemplates.put(nodeTypeTemplate3, template3);
+ *
+ * topology.setNodeTemplates(nodeTemplates); resourceDAO.save(topology);
+ *
+ * TopologyTemplate topologyTemplate = new TopologyTemplate();
+ * topologyTemplate.setId(topologyTemplateName);
+ * topologyTemplate.setName(topologyTemplateName);
+ * topologyTemplate.setTopologyId(topology.getId());
+ * topologyTemplate.setDescription("my topology template");
+ * resourceDAO.save(topologyTemplate);
+ *
+ * String strData = "qweqwqweqw34e4wrwer"; ArtifactData arData = new
+ * ArtifactData("artifact1", nodeType, nodeTypeVersion, "YANG",
+ * strData.getBytes(), strData.getBytes(), "Marina"); ArtifactData arData1 =
+ * new ArtifactData("artifact2", nodeType, nodeTypeVersion, "YANG",
+ * strData.getBytes(), strData.getBytes(), "Marina"); ResourceUploadStatus
+ * status = daoUploader.saveArtifact(arData, true); status =
+ * daoUploader.saveArtifact(arData1, true);
+ *
+ * ArtifactData arData3 = new ArtifactData("artifact1", nodeType2,
+ * nodeTypeVersion2, "YANG", strData.getBytes(), strData.getBytes(),
+ * "Marina"); status = daoUploader.saveArtifact(arData3, true);
+ *
+ * ArtifactData arData4 = new ArtifactData("artifact2", nodeType2,
+ * nodeTypeVersion2, "YANG", strData.getBytes(), strData.getBytes(),
+ * "Marina"); status = daoUploader.saveArtifact(arData4, true);
+ *
+ * ServiceArtifactData serviceArData = new
+ * ServiceArtifactData("serviceArData", topologyTemplateName,
+ * topologyTemplateVersion, nodeTypeTemplate1, nodeType, nodeTypeVersion,
+ * "YANG", strData.getBytes(), strData.getBytes(), "Marina",
+ * arData.getId());
+ *
+ * status = daoUploader.saveServiceArtifact(serviceArData, true);
+ *
+ * ServiceArtifactData serviceArData1 = new
+ * ServiceArtifactData("serviceArData1", topologyTemplateName,
+ * topologyTemplateVersion, nodeTypeTemplate2, nodeType2, nodeTypeVersion2,
+ * "YANG", strData.getBytes(), strData.getBytes(), "Marina",
+ * arData4.getId());
+ *
+ * status = daoUploader.saveServiceArtifact(serviceArData1, true);
+ *
+ *
+ * } catch (Exception e) { // TODO Auto-generated catch block
+ * e.printStackTrace(); }
+ *
+ * }
+ *
+ * private void prepareTestTopolgyService(){
+ *
+ * List<String> listCap = new ArrayList<String>();
+ * listCap.add("very_evil test"); List<String> listCap1 = new
+ * ArrayList<String>(); listCap.add("evil test"); try{ // Initialize test
+ * data IndexedNodeType indexedNodeType = new IndexedNodeType();
+ * CSARDependency dep = new CSARDependency(); dep.setName(nodeType +
+ * " test"); dep.setVersion(nodeTypeVersion);
+ * indexedNodeType.setElementId(nodeType + " test");
+ * indexedNodeType.setArchiveName(nodeType + " test");
+ * indexedNodeType.setArchiveVersion(nodeTypeVersion);
+ * indexedNodeType.setCreationDate(new Date());
+ * indexedNodeType.setLastUpdateDate(new Date());
+ * indexedNodeType.setDefaultCapabilities(listCap);
+ * resourceDAO.save(indexedNodeType);
+ *
+ *
+ * IndexedNodeType indexedNodeType1 = new IndexedNodeType();
+ * indexedNodeType1.setElementId(nodeType2 + " test");
+ * indexedNodeType1.setArchiveName(nodeType2 + " test");
+ * indexedNodeType1.setArchiveVersion(nodeTypeVersion2); CSARDependency dep1
+ * = new CSARDependency(); dep1.setName(nodeType2 + " test");
+ * dep1.setVersion(nodeTypeVersion2); indexedNodeType1.setCreationDate(new
+ * Date()); indexedNodeType1.setLastUpdateDate(new Date());
+ * indexedNodeType1.setDefaultCapabilities(listCap1);
+ * resourceDAO.save(indexedNodeType1);
+ *
+ *
+ * indexedNodeType.setElementId(nodeType3 + " test");
+ * indexedNodeType.setArchiveName(nodeType3 + " test");
+ * indexedNodeType.setArchiveVersion(nodeNypeVersion3); CSARDependency dep2
+ * = new CSARDependency(); dep2.setName(nodeType3 + " test");
+ * dep2.setVersion(nodeNypeVersion3); indexedNodeType.setCreationDate(new
+ * Date()); indexedNodeType.setLastUpdateDate(new Date());
+ * indexedNodeType.setDefaultCapabilities(null);
+ * resourceDAO.save(indexedNodeType); String osgiliath100Id =
+ * indexedNodeType.getId();
+ *
+ * Topology topology = new Topology(); topology.setId(topologyId + " test");
+ * Set<CSARDependency> dependencies = new HashSet<CSARDependency>();
+ * dependencies.add(dep); dependencies.add(dep2); dependencies.add(dep1);
+ * topology.setDependencies(dependencies); Map<String, NodeTemplate>
+ * nodeTemplates = new HashMap <String, NodeTemplate>();
+ *
+ * NodeTemplate template1 = new NodeTemplate(nodeType + " test", null, null,
+ * null, null, null, null); template1.setName(nodeTypeTemplate1 + " test");
+ * nodeTemplates.put(nodeTypeTemplate1 + " test", template1 );
+ *
+ * NodeTemplate template2 = new NodeTemplate(nodeType2 + " test", null,
+ * null, null, null, null, null); template2.setName(nodeTypeTemplate2 +
+ * " test" ); nodeTemplates.put(nodeTypeTemplate2 + " test", template2 );
+ *
+ * NodeTemplate template3 = new NodeTemplate(nodeType, null, null, null,
+ * null, null, null); template3.setName(nodeTypeTemplate3 + " test" );
+ * nodeTemplates.put(nodeTypeTemplate3 + " test", template3);
+ *
+ * topology.setNodeTemplates(nodeTemplates); resourceDAO.save(topology);
+ *
+ * TopologyTemplate topologyTemplate = new TopologyTemplate();
+ * topologyTemplate.setId(topologyTemplateName + " test");
+ * topologyTemplate.setName(topologyTemplateName + " test");
+ * topologyTemplate.setTopologyId(topology.getId());
+ * topologyTemplate.setDescription("my topology template");
+ * resourceDAO.save(topologyTemplate);
+ *
+ * String strData = "qweqwqweqw34e4wrwer"; ArtifactData arData = new
+ * ArtifactData("artifact1 test", nodeType + " test", nodeTypeVersion,
+ * "YANG", strData.getBytes(), strData.getBytes(), "Marina"); ArtifactData
+ * arData1 = new ArtifactData("artifact2 test", nodeType + " test",
+ * nodeTypeVersion, "YANG", strData.getBytes(), strData.getBytes(),
+ * "Marina"); ResourceUploadStatus status = daoUploader.saveArtifact(arData,
+ * true); status = daoUploader.saveArtifact(arData1, true);
+ *
+ * ArtifactData arData3 = new ArtifactData("artifact1 test", nodeType2 +
+ * " test", nodeTypeVersion2, "YANG", strData.getBytes(),
+ * strData.getBytes(), "Marina"); status = daoUploader.saveArtifact(arData3,
+ * true);
+ *
+ * ArtifactData arData4 = new ArtifactData("artifact2 test", nodeType2 +
+ * " test", nodeTypeVersion2, "YANG", strData.getBytes(),
+ * strData.getBytes(), "Marina"); status = daoUploader.saveArtifact(arData4,
+ * true);
+ *
+ * ServiceArtifactData serviceArData = new
+ * ServiceArtifactData("serviceArData test" , topologyTemplateName +
+ * " test", topologyTemplateVersion, nodeTypeTemplate1 + " test", nodeType +
+ * " test", nodeTypeVersion, "YANG", strData.getBytes(), strData.getBytes(),
+ * "Marina", arData.getId());
+ *
+ * status = daoUploader.saveServiceArtifact(serviceArData, true);
+ *
+ * ServiceArtifactData serviceArData1 = new
+ * ServiceArtifactData("serviceArData1 test", topologyTemplateName +
+ * " test", topologyTemplateVersion, nodeTypeTemplate2 + " test", nodeType2
+ * + " test", nodeTypeVersion2, "YANG", strData.getBytes(),
+ * strData.getBytes(), "Marina", arData4.getId());
+ *
+ * status = daoUploader.saveServiceArtifact(serviceArData1, true);
+ *
+ *
+ * } catch (Exception e) { // TODO Auto-generated catch block
+ * e.printStackTrace(); }
+ *
+ * }
+ */
+
+ private void clearIndex(String indexName, Class<?> clazz) throws InterruptedException {
+
+ DeleteIndexResponse actionGet = esclient.getClient().admin().indices().delete(new DeleteIndexRequest(indexName))
+ .actionGet();
+ assertTrue(actionGet.isAcknowledged());
+ }
+
+}
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/AuditingDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/AuditingDaoTest.java
new file mode 100644
index 0000000000..06d26f79f9
--- /dev/null
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/AuditingDaoTest.java
@@ -0,0 +1,463 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources;
+
+import fj.data.Either;
+import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
+import org.elasticsearch.action.search.SearchResponse;
+import org.elasticsearch.index.query.MatchAllQueryBuilder;
+import org.elasticsearch.search.SearchHit;
+import org.elasticsearch.search.SearchHits;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig.IndicesTimeFrequencyEntry;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
+import org.openecomp.sdc.be.dao.impl.AuditingDao;
+import org.openecomp.sdc.be.resources.data.auditing.*;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestExecutionListeners;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
+import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
+import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import static org.junit.Assert.*;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:application-context-test.xml")
+@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class,
+ DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class })
+public class AuditingDaoTest {
+ private static Logger log = LoggerFactory.getLogger(AuditingDaoTest.class.getName());
+ @Resource(name = "elasticsearch-client")
+ private ElasticSearchClient esclient;
+
+ @Resource(name = "auditingDao")
+ private AuditingDao auditingDao;
+
+ private static ConfigurationManager configurationManager;
+ // private static Map<AuditingFieldsKeysEnum, String> auditField2esField;
+
+ @BeforeClass
+ public static void setupBeforeClass() {
+
+ ExternalConfiguration.setAppName("catalog-dao");
+ String appConfigDir = "src/test/resources/config/catalog-dao";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
+ appConfigDir);
+ configurationManager = new ConfigurationManager(configurationSource);
+ // initAudit2EsMap();
+ }
+
+ @After
+ public void tearDown() {
+ deleteOldIndexes();
+ }
+
+ @Before
+ public void setup() {
+ auditingDao.setConfigurationManager(configurationManager);
+ deleteOldIndexes();
+ }
+
+ private void deleteOldIndexes() {
+ DeleteIndexResponse deleteResponse = esclient.getClient().admin().indices()
+ .prepareDelete(auditingDao.getIndexPrefix() + "*").execute().actionGet();
+ if (!deleteResponse.isAcknowledged()) {
+ log.debug("Couldn't delete old auditing indexes!");
+ assertTrue(false);
+ }
+ }
+
+ // @Test
+ public void testAddUpdateAdminEventMinute() {
+
+ String timestamp = "2015-06-23 13:34:53.123";
+
+ String creationPeriod = Constants.MINUTE;
+ String expectedIndexName = auditingDao.getIndexPrefix() + "-2015-06-23-13-34";
+ assertTrue(!esclient.getClient().admin().indices().prepareExists(expectedIndexName).execute().actionGet()
+ .isExists());
+ Map<AuditingFieldsKeysEnum, Object> params = getUserAdminEventParams(timestamp);
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, UserAdminEvent.class);
+ params = getUserAccessEventParams(timestamp);
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, UserAccessEvent.class);
+ params = getResourceAdminEventParams(timestamp, "addResource");
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, ResourceAdminEvent.class);
+ }
+
+ // @Test
+ public void testAddUpdateAdminEventYearly() {
+
+ String timestamp = "2016-06-23 13:34:53.123";
+ String creationPeriod = Constants.YEAR;
+ String expectedIndexName = auditingDao.getIndexPrefix() + "-2016";
+ assertTrue(!esclient.getClient().admin().indices().prepareExists(expectedIndexName).execute().actionGet()
+ .isExists());
+ Map<AuditingFieldsKeysEnum, Object> params = getUserAdminEventParams(timestamp);
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, UserAdminEvent.class);
+ params = getUserAccessEventParams(timestamp);
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, UserAccessEvent.class);
+ params = getResourceAdminEventParams(timestamp, "addResource");
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, ResourceAdminEvent.class);
+ }
+
+ @Test
+ public void testGetDistributionStatusEvent() {
+
+ String timestamp1 = "2016-06-23 13:34:53.123";
+ String creationPeriod = Constants.MONTH;
+ String expectedIndexName1 = auditingDao.getIndexPrefix() + "-2016-06";
+ assertTrue(!esclient.getClient().admin().indices().prepareExists(expectedIndexName1).execute().actionGet()
+ .isExists());
+ Map<AuditingFieldsKeysEnum, Object> params = getDistributionStatusEventParams(timestamp1);
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName1, DistributionStatusEvent.class);
+ String timestamp2 = "2015-06-23 13:34:53.123";
+
+ String expectedIndexName2 = auditingDao.getIndexPrefix() + "-2015-06";
+ assertTrue(!esclient.getClient().admin().indices().prepareExists(expectedIndexName2).execute().actionGet()
+ .isExists());
+ Map<AuditingFieldsKeysEnum, Object> params2 = getDistributionStatusEventParams(timestamp2);
+ testCreationPeriodScenario(params2, creationPeriod, expectedIndexName2, DistributionStatusEvent.class);
+ Either<List<ESTimeBasedEvent>, ActionStatus> status = auditingDao.getListOfDistributionStatuses("123-456");
+ assertEquals(2, status.left().value().size());
+ }
+
+ @Test
+ public void testGetCountAdminEventMonthly() {
+
+ String timestamp1 = "2016-06-23 13:34:53.123";
+ String timestamp2 = "2015-06-23 13:34:53.123";
+ String creationPeriod = Constants.MONTH;
+ String expectedIndexName1 = auditingDao.getIndexPrefix() + "-2016-06";
+ assertTrue(!esclient.getClient().admin().indices().prepareExists(expectedIndexName1).execute().actionGet()
+ .isExists());
+ String expectedIndexName2 = auditingDao.getIndexPrefix() + "-2015-06";
+ assertTrue(!esclient.getClient().admin().indices().prepareExists(expectedIndexName2).execute().actionGet()
+ .isExists());
+
+ Map<AuditingFieldsKeysEnum, Object> params1 = getUserAdminEventParams(timestamp1);
+ testCreationPeriodScenario(params1, creationPeriod, expectedIndexName1, UserAdminEvent.class);
+ Map<AuditingFieldsKeysEnum, Object> params2 = getUserAdminEventParams(timestamp2);
+ testCreationPeriodScenario(params2, creationPeriod, expectedIndexName2, UserAdminEvent.class);
+
+ long count = auditingDao.count(UserAdminEvent.class, new MatchAllQueryBuilder());
+ log.debug("Testing auditing count {}", count);
+ assertEquals(2, count);
+ }
+
+ @Test
+ public void testServiceDistributionStatuses() {
+
+ String timestamp = "2016-06-23 13:34:53.123";
+ String creationPeriod = Constants.MONTH;
+ String expectedIndexName = auditingDao.getIndexPrefix() + "-2016-06";
+ assertTrue(!esclient.getClient().admin().indices().prepareExists(expectedIndexName).execute().actionGet()
+ .isExists());
+ Map<AuditingFieldsKeysEnum, Object> params = getUserAdminEventParams(timestamp);
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, UserAdminEvent.class);
+ params = getUserAccessEventParams(timestamp);
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, UserAccessEvent.class);
+ params = getResourceAdminEventParams(timestamp, "DRequest");
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, ResourceAdminEvent.class);
+ params = getDistributionNotificationEventParams(timestamp);
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, DistributionNotificationEvent.class);
+ Either<List<ESTimeBasedEvent>, ActionStatus> status = auditingDao
+ .getServiceDistributionStatusesList("SeviceId");
+ log.debug("Testing auditing count {}", status);
+ }
+
+ @Test
+ public void testAddUpdateAdminEventMonthly() {
+
+ String timestamp = "2016-06-23 13:34:53.123";
+ String creationPeriod = Constants.MONTH;
+ String expectedIndexName = auditingDao.getIndexPrefix() + "-2016-06";
+ assertTrue(!esclient.getClient().admin().indices().prepareExists(expectedIndexName).execute().actionGet()
+ .isExists());
+ Map<AuditingFieldsKeysEnum, Object> params = getUserAdminEventParams(timestamp);
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, UserAdminEvent.class);
+ params = getUserAccessEventParams(timestamp);
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, UserAccessEvent.class);
+ params = getResourceAdminEventParams(timestamp, "addResource");
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, ResourceAdminEvent.class);
+ }
+
+ private SearchResponse testCreationPeriodScenario(Map<AuditingFieldsKeysEnum, Object> params, String creationPeriod,
+ String expectedIndexName, Class<? extends AuditingGenericEvent> clazz) {
+
+ String typeName = clazz.getSimpleName().toLowerCase();
+ log.debug("Testing auditing type {}", typeName);
+ setCreationPeriod(creationPeriod);
+ ActionStatus saveUserAdminEvent = auditingDao.addRecord(params, typeName);
+ assertEquals(ActionStatus.OK, saveUserAdminEvent);
+ assertTrue(esclient.getClient().admin().indices().prepareExists(expectedIndexName).execute().actionGet()
+ .isExists());
+ MatchAllQueryBuilder matchAllQueryBuilder = new MatchAllQueryBuilder();
+
+ SearchResponse searchResponse = esclient.getClient().prepareSearch(expectedIndexName).setTypes(typeName)
+ .setQuery(matchAllQueryBuilder).execute().actionGet();
+
+ SearchHits hits = searchResponse.getHits();
+ assertEquals(1, hits.getTotalHits());
+ log.debug("Checking that all expected fields are properly persisted");
+ validateHitValues(params, hits.getAt(0));
+ log.debug("testCreationPeriodScenario successful");
+ return searchResponse;
+ }
+
+ private void validateHitValues(Map<AuditingFieldsKeysEnum, Object> params, SearchHit searchHit) {
+ Map<String, Object> source = searchHit.getSource();
+ log.debug("Hit source is {}", searchHit.sourceAsString());
+ for (Entry<AuditingFieldsKeysEnum, Object> paramsEntry : params.entrySet()) {
+ AuditingFieldsKeysEnum key = paramsEntry.getKey();
+ log.debug("Testing auditing field {}", key.name());
+ Object value = paramsEntry.getValue();
+ // assertEquals(value, source.get(auditField2esField.get(key)));
+ assertEquals(value, source.get(key.getDisplayName()));
+ }
+ }
+
+ private void setCreationPeriod(String creationPeriod) {
+ Configuration configuration = configurationManager.getConfiguration();
+ List<IndicesTimeFrequencyEntry> indicesTimeFrequencyEntries = new ArrayList<>();
+ IndicesTimeFrequencyEntry indicesTimeFrequencyEntry = new IndicesTimeFrequencyEntry();
+ indicesTimeFrequencyEntry.setIndexPrefix("auditingevents");
+ indicesTimeFrequencyEntry.setCreationPeriod(creationPeriod);
+ configuration.getElasticSearch().setIndicesTimeFrequency(indicesTimeFrequencyEntries);
+ }
+
+ private Map<AuditingFieldsKeysEnum, Object> getUserAdminEventParams(String timestamp) {
+
+ Map<AuditingFieldsKeysEnum, Object> params = new HashMap<AuditingFieldsKeysEnum, Object>();
+ String action = "updateUser";
+ String modifierName = "moshe moshe";
+ String modifierUid = "mosheUid";
+ String userUid = "mosheUid";
+ String userBeforeName = "moshe moshe";
+ String userBeforeEmail = "moshe@moshe1.com";
+ String userBeforeRole = "TESTER";
+ String userAfterName = "moshe moshe";
+ String userAfterEmail = "moshe@moshe2.com";
+ String userAfterRole = "TESTER";
+ String userStatus = "200";
+ String userDesc = "OK";
+
+ params.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action);
+ params.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifierName + '(' + modifierUid + ')');
+ params.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, userUid);
+ params.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE,
+ userUid + ", " + userBeforeName + ", " + userBeforeEmail + ", " + userBeforeRole);
+ params.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER,
+ userUid + ", " + userAfterName + ", " + userAfterEmail + ", " + userAfterRole);
+ params.put(AuditingFieldsKeysEnum.AUDIT_STATUS, userStatus);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DESC, userDesc);
+ params.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP, timestamp);
+
+ return params;
+ }
+
+ private Map<AuditingFieldsKeysEnum, Object> getUserAccessEventParams(String timestamp) {
+
+ Map<AuditingFieldsKeysEnum, Object> params = new HashMap<AuditingFieldsKeysEnum, Object>();
+ String action = "userAccess";
+ String userUid = "mosheUid";
+ String userName = "moshe moshe";
+ String userStatus = "200";
+ String userDesc = "OK";
+
+ params.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action);
+ params.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, userName + '(' + userUid + ')');
+ params.put(AuditingFieldsKeysEnum.AUDIT_STATUS, userStatus);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DESC, userDesc);
+ params.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP, timestamp);
+
+ return params;
+ }
+
+ private Map<AuditingFieldsKeysEnum, Object> getResourceAdminEventParams(String timestamp, String action) {
+
+ Map<AuditingFieldsKeysEnum, Object> params = new HashMap<AuditingFieldsKeysEnum, Object>();
+
+ String modifierName = "moshe moshe";
+ String modifierUid = "mosheUid";
+ String resourceName = "Centos";
+ String resourceType = "Resource";
+ String currState = "READY_FOR_CERTIFICATION";
+ String prevState = "CHECKED_OUT";
+ String currVersion = "1.1.4";
+ String prevVersion = "1.1.3";
+ String status = "200";
+ String desc = "OK";
+ String distributionId = "123-456";
+ String serviceId = "SeviceId";
+
+ params.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action);
+ params.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifierName);
+ params.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifierUid);
+ params.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceName);
+ params.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, resourceType);
+ params.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, currState);
+ params.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, prevState);
+ params.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, currVersion);
+ params.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, prevVersion);
+ params.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DESC, desc);
+ params.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP, timestamp);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId);
+ params.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceId);
+
+ return params;
+ }
+
+ private Map<AuditingFieldsKeysEnum, Object> getDistributionStatusEventParams(String timestamp) {
+
+ Map<AuditingFieldsKeysEnum, Object> params = new HashMap<AuditingFieldsKeysEnum, Object>();
+ String action = "DStatus";
+ String modifierName = "moshe moshe";
+ String modifierUid = "mosheUid";
+ String topicName = "Centos";
+ String serviceId = "SeviceId";
+ String resourceUrl = "resourceUrl";
+ String distributionId = "123-456";
+
+ String status = "200";
+ String desc = "OK";
+
+ params.put(AuditingFieldsKeysEnum.AUDIT_DESC, desc);
+ params.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP, timestamp);
+ params.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ params.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, modifierUid);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, resourceUrl);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, timestamp);
+ params.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceId);
+
+ return params;
+ }
+
+ // @Test
+ public void getListOfDistributionByActionTest() {
+
+ String timestamp = "2016-06-23 13:34:53.123";
+ String distributionId = "123-456";
+
+ String creationPeriod = Constants.MONTH;
+ String expectedIndexName = auditingDao.getIndexPrefix() + "-2016-06";
+ assertTrue(!esclient.getClient().admin().indices().prepareExists(expectedIndexName).execute().actionGet()
+ .isExists());
+
+ // Client client = esclient.getClient();
+ // final CreateIndexRequestBuilder createIndexRequestBuilder =
+ // client.admin().indices().prepareCreate(expectedIndexName);
+ // final XContentBuilder mappingBuilder =
+ // jsonBuilder().startObject().startObject("resourceadminevent")
+ // .startObject("_ttl").field("enabled", "true").field("default",
+ // "1s").endObject().endObject()
+ // .endObject();
+ // System.out.println(mappingBuilder.string());
+ // createIndexRequestBuilder.addMapping(documentType, mappingBuilder);
+ //
+ // // MAPPING DONE
+ // createIndexRequestBuilder.execute().actionGet();
+ //
+ //
+
+ Map<AuditingFieldsKeysEnum, Object> params = getResourceAdminEventParams(timestamp, "DRequest");
+ params.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId);
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, ResourceAdminEvent.class);
+ params = getDistributionNotificationEventParams(timestamp);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId);
+
+ testCreationPeriodScenario(params, creationPeriod, expectedIndexName, DistributionNotificationEvent.class);
+
+ Either<List<ESTimeBasedEvent>, ActionStatus> distributionByAction = auditingDao
+ .getListOfDistributionByAction(distributionId, "DRequest", "200", ResourceAdminEvent.class);
+ assertTrue(distributionByAction.isLeft());
+ assertFalse(distributionByAction.left().value().isEmpty());
+
+ distributionByAction = auditingDao.getListOfDistributionByAction(distributionId, "DNotify", "200",
+ DistributionNotificationEvent.class);
+ assertTrue(distributionByAction.isLeft());
+ assertFalse(distributionByAction.left().value().isEmpty());
+
+ }
+
+ private Map<AuditingFieldsKeysEnum, Object> getDistributionNotificationEventParams(String timestamp) {
+
+ Map<AuditingFieldsKeysEnum, Object> params = new HashMap<AuditingFieldsKeysEnum, Object>();
+
+ String action = "DNotify";
+ String modifierName = "moshe moshe";
+ String modifierUid = "mosheUid";
+ String resourceName = "Centos";
+ String resourceType = "Resource";
+
+ String currVersion = "1.1.4";
+ String currState = "READY_FOR_CERTIFICATION";
+ String status = "200";
+ String desc = "OK";
+ String did = "1027";
+ String topicName = "Centos";
+ String serviceId = "SeviceId";
+ String requestId = "12364";
+
+ params.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action);
+ params.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, requestId);
+ params.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifierUid);
+ params.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifierName);
+ params.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceName);
+ params.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, resourceType);
+ params.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, currState);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName);
+ params.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, currVersion);
+ params.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DESC, desc);
+ params.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP, timestamp);
+ params.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, did);
+ params.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceId);
+ return params;
+ }
+
+}
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/CassandraTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/CassandraTest.java
new file mode 100644
index 0000000000..caaf0702a5
--- /dev/null
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/CassandraTest.java
@@ -0,0 +1,74 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources;
+
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.mapping.Mapper;
+import com.datastax.driver.mapping.MappingManager;
+
+import org.openecomp.sdc.be.dao.Account;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class CassandraTest {
+ private static Logger log = LoggerFactory.getLogger(CassandraTest.class.getName());
+ private Cluster cluster;
+
+ // #\@Test
+ public void testCrud() {
+ String node = "mtanjv9sdcg44";
+
+ cluster = Cluster.builder().addContactPoint(node).build();
+
+ // Query
+ String query = "CREATE KEYSPACE IF NOT EXISTS dstest WITH replication "
+ + "= {'class':'SimpleStrategy', 'replication_factor':1};";
+
+ String queryTable = "CREATE TABLE IF NOT EXISTS accounts(email varchar PRIMARY KEY, name varchar);";
+
+ Session session = cluster.connect();
+ // Executing the query
+ session.execute(query);
+ // //using the KeySpace
+ session.execute("USE dstest");
+ session.execute(queryTable);
+
+ Mapper<Account> mapper = new MappingManager(session).mapper(Account.class);
+ Account account = new Account("John Doe", "jd@example.com");
+ // Class<? extends Account> class1 = account.getClass();
+ // Class class2 = Account.class;
+ mapper.save(account);
+
+ Account whose = mapper.get("jd@example.com");
+ log.debug("Account name: {}", whose.getName());
+
+ account.setName("Samanta Smit");
+ mapper.save(account);
+ whose = mapper.get("jd@example.com");
+ log.debug("Account name: {}", whose.getName());
+
+ mapper.delete(account);
+ whose = mapper.get("jd@example.com");
+
+ cluster.close();
+ }
+}
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ESUsersDAOTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ESUsersDAOTest.java
new file mode 100644
index 0000000000..a99acbe2b7
--- /dev/null
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ESUsersDAOTest.java
@@ -0,0 +1,64 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources;
+
+//@RunWith(SpringJUnit4ClassRunner.class)
+//@ContextConfiguration("classpath:application-context-test.xml")
+//@TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class})
+public class ESUsersDAOTest {
+
+ // @Resource
+ // ElasticSearchClient esclient;
+ //
+ //// @Resource(name = "users-dao")
+ // private IUsersDAO usersDao;
+
+ // @Test
+ public void testNewUserStub() {
+
+ }
+
+ // @Test
+ public void testNewUser() {
+ // if( usersDao == null ){
+ // assertTrue(false);
+ // }
+ //
+ // String id = "yhufksd57834601";
+ // UserData userData = new UserData("Myname", "Mylastname", id, "email",
+ // "Tester");
+ //
+ // ActionStatus saveUserData = usersDao.saveUserData(userData);
+ // assertEquals(saveUserData, ActionStatus.OK);
+ //
+ // Either<UserData, ActionStatus> statusFromEs =
+ // usersDao.getUserData(id);
+ // assertTrue(statusFromEs.isLeft() );
+ // UserData fromEs = statusFromEs.left().value();
+ // assertNotNull(fromEs);
+ // assertEquals(userData, fromEs);
+ //
+ //
+ // usersDao.deleteUserData(id);
+
+ }
+
+}
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java
new file mode 100644
index 0000000000..a4110f5be3
--- /dev/null
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java
@@ -0,0 +1,721 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.resources;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.Resource;
+
+import org.apache.commons.configuration.BaseConfiguration;
+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.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.resources.data.AdditionalInfoParameterData;
+import org.openecomp.sdc.be.resources.data.ArtifactData;
+import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
+import org.openecomp.sdc.be.resources.data.GraphNodeLock;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
+import org.openecomp.sdc.be.resources.data.UserData;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.api.UserRoleEnum;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestExecutionListeners;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
+import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
+import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
+
+import com.google.gson.Gson;
+import com.thinkaurelius.titan.core.PropertyKey;
+import com.thinkaurelius.titan.core.TitanEdge;
+import com.thinkaurelius.titan.core.TitanFactory;
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+import com.thinkaurelius.titan.core.attribute.Text;
+import com.thinkaurelius.titan.core.schema.TitanManagement;
+
+import fj.data.Either;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:application-context-test.xml")
+@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class,
+ DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class })
+public class TitanGenericDaoTest {
+ private static Logger log = LoggerFactory.getLogger(TitanGenericDaoTest.class.getName());
+ private static ConfigurationManager configurationManager;
+
+ @Resource(name = "titan-generic-dao")
+ private TitanGenericDao titanDao;
+
+ @BeforeClass
+ public static void setupBeforeClass() {
+ ExternalConfiguration.setAppName("catalog-dao");
+ String appConfigDir = "src/test/resources/config/catalog-dao";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
+ appConfigDir);
+ configurationManager = new ConfigurationManager(configurationSource);
+ configurationManager.getConfiguration()
+ .setTitanCfgFile("../catalog-be/src/main/resources/config/titan.properties");
+ configurationManager.getConfiguration().setTitanInMemoryGraph(true);
+ }
+
+ // @Test
+ public void testcheckEdgeProps() {
+ TitanGraph graph = titanDao.getGraph().left().value();
+ TitanVertex v1 = graph.addVertex();
+ v1.property("prop1", 123);
+ TitanVertex v2 = graph.addVertex();
+ v2.property("prop1", 456);
+ TitanEdge addEdge = v1.addEdge("label11", v2);
+ addEdge.property("edgeProp", "my prop edge");
+ graph.tx().commit();
+
+ Either<TitanVertex, TitanOperationStatus> v11 = titanDao.getVertexByProperty("prop1", 123);
+ Iterator<Edge> edges = v11.left().value().edges(Direction.OUT, "label11");
+ Edge edge = edges.next();
+ // String value = (String)edge.value("edgeProp");
+ String value = (String) titanDao.getProperty(edge, "edgeProp");
+ log.debug(value);
+
+ }
+
+ @Test
+ public void testCrudNode() {
+
+ String id = "user12345abc";
+ UserData userData = new UserData("Myname123", "Mylastname", id, "email123", "Tester",
+ UserStatusEnum.ACTIVE.name(), null);
+
+ Either<UserData, TitanOperationStatus> newNode = titanDao.createNode(userData, UserData.class);
+
+ assertTrue(newNode.isLeft());
+
+ log.debug("{}", newNode.left().value());
+
+ titanDao.commit();
+
+ ImmutablePair<String, Object> keyValueId = userData.getKeyValueId();
+ Either<UserData, TitanOperationStatus> node = titanDao.getNode(keyValueId.getKey(), keyValueId.getValue(),
+ UserData.class);
+ titanDao.commit();
+ assertTrue(node.isLeft());
+ log.debug("{}", node.left().value());
+
+ userData.setRole("Designer");
+ node = titanDao.updateNode(userData, UserData.class);
+ assertTrue(node.isLeft());
+ log.debug("{}", node.left().value());
+ assertEquals(null, "Designer", node.left().value().getRole());
+ titanDao.commit();
+
+ node = titanDao.deleteNode(userData, UserData.class);
+ assertTrue(node.isLeft());
+ log.debug("{}", node.left().value());
+ titanDao.commit();
+
+ node = titanDao.getNode(keyValueId.getKey(), keyValueId.getValue(), UserData.class);
+ assertTrue(node.isRight());
+ log.debug("{}", node.right().value());
+
+ }
+
+ @Test
+ public void testGetByCategoryAndAll() {
+
+ // create 2 nodes
+ String id = "user12345abc";
+ UserData userData1 = new UserData("Myname123", "Mylastname", id, "email123", "Tester",
+ UserStatusEnum.ACTIVE.name(), null);
+
+ Either<UserData, TitanOperationStatus> node1 = titanDao.createNode(userData1, UserData.class);
+ assertTrue(node1.isLeft());
+ log.debug("{}", node1.left().value());
+
+ id = "userdfkoer45abc";
+ UserData userData2 = new UserData("Mynadyhme123", "Mylasghtname", id, "emaighdl123", "Designer",
+ UserStatusEnum.ACTIVE.name(), null);
+ Either<UserData, TitanOperationStatus> node2 = titanDao.createNode(userData2, UserData.class);
+ assertTrue(node2.isLeft());
+ log.debug("{}", node2.left().value());
+
+ titanDao.commit();
+
+ ImmutablePair<String, Object> keyValueId1 = userData1.getKeyValueId();
+ // get first node
+ Either<UserData, TitanOperationStatus> node = titanDao.getNode(keyValueId1.getKey(), keyValueId1.getValue(),
+ UserData.class);
+ assertTrue(node.isLeft());
+ log.debug("{}", node.left().value());
+ titanDao.commit();
+
+ // get all must be 2 + 1 default user = 3
+ Either<List<UserData>, TitanOperationStatus> all = titanDao.getAll(NodeTypeEnum.User, UserData.class);
+ assertTrue(all.isLeft());
+ assertTrue(all.left().value().size() > 0);
+
+ log.debug("{}", all.left().value());
+
+ Map<String, Object> props = new HashMap<String, Object>();
+
+ props.put(keyValueId1.getKey(), keyValueId1.getValue());
+
+ // get by criteria. must be 1
+ Either<List<UserData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.User, props,
+ UserData.class);
+ assertTrue(byCriteria.isLeft());
+ assertEquals(1, byCriteria.left().value().size());
+
+ log.debug("{}", byCriteria.left().value());
+
+ // delete all nodes
+ node = titanDao.deleteNode(userData1, UserData.class);
+ assertTrue(node.isLeft());
+ node = titanDao.deleteNode(userData2, UserData.class);
+ assertTrue(node.isLeft());
+ }
+
+ @Test
+ public void testGetEdgesForNode() {
+ String id = "user12345abc";
+ UserData userData = new UserData("Myname123", "Mylastname", id, "email123", UserRoleEnum.ADMIN.name(),
+ UserStatusEnum.ACTIVE.name(), null);
+ titanDao.createNode(userData, UserData.class);
+ ResourceMetadataData resourceData = new ResourceMetadataData();
+ resourceData.getMetadataDataDefinition().setName("resourceForLock");
+ resourceData.getMetadataDataDefinition().setVersion("0.1");
+ resourceData.getMetadataDataDefinition().setState("newState");
+ resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "."
+ + resourceData.getMetadataDataDefinition().getVersion());
+
+ titanDao.createNode(resourceData, ResourceMetadataData.class);
+ titanDao.createRelation(userData, resourceData, GraphEdgeLabels.LAST_MODIFIER, null);
+ titanDao.commit();
+
+ Either<List<Edge>, TitanOperationStatus> eitherEdges = titanDao.getEdgesForNode(userData, Direction.OUT);
+ assertTrue(eitherEdges.isLeft());
+ assertTrue(eitherEdges.left().value().size() == 1);
+
+ eitherEdges = titanDao.getEdgesForNode(userData, Direction.IN);
+ assertTrue(eitherEdges.isLeft());
+ assertTrue(eitherEdges.left().value().size() == 0);
+
+ eitherEdges = titanDao.getEdgesForNode(resourceData, Direction.OUT);
+ assertTrue(eitherEdges.isLeft());
+ assertTrue(eitherEdges.left().value().size() == 0);
+
+ eitherEdges = titanDao.getEdgesForNode(resourceData, Direction.IN);
+ assertTrue(eitherEdges.isLeft());
+ assertTrue(eitherEdges.left().value().size() == 1);
+
+ eitherEdges = titanDao.getEdgesForNode(resourceData, Direction.BOTH);
+ assertTrue(eitherEdges.isLeft());
+ assertTrue(eitherEdges.left().value().size() == 1);
+
+ eitherEdges = titanDao.getEdgesForNode(userData, Direction.BOTH);
+ assertTrue(eitherEdges.isLeft());
+ assertTrue(eitherEdges.left().value().size() == 1);
+
+ titanDao.deleteNode(userData, UserData.class);
+ titanDao.deleteNode(resourceData, ResourceMetadataData.class);
+ titanDao.commit();
+ }
+
+ @Test
+ public void testLockElement() {
+
+ ResourceMetadataData resourceData = new ResourceMetadataData();
+
+ resourceData.getMetadataDataDefinition().setName("resourceForLock");
+ resourceData.getMetadataDataDefinition().setVersion("0.1");
+ resourceData.getMetadataDataDefinition().setState("newState");
+ resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "."
+ + resourceData.getMetadataDataDefinition().getVersion());
+
+ Either<ResourceMetadataData, TitanOperationStatus> resource1 = titanDao.createNode(resourceData,
+ ResourceMetadataData.class);
+ assertTrue(resource1.isLeft());
+ titanDao.commit();
+ String lockId = "lock_" + resourceData.getLabel() + "_" + resource1.left().value().getUniqueId();
+
+ Either<GraphNodeLock, TitanOperationStatus> nodeLock = titanDao
+ .getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class);
+ assertTrue(nodeLock.isRight());
+ assertEquals(TitanOperationStatus.NOT_FOUND, nodeLock.right().value());
+
+ TitanOperationStatus status = titanDao.lockElement(resourceData);
+ assertEquals(TitanOperationStatus.OK, status);
+
+ nodeLock = titanDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class);
+ assertTrue(nodeLock.isLeft());
+ assertEquals(lockId, nodeLock.left().value().getUniqueId());
+
+ titanDao.commit();
+
+ status = titanDao.lockElement(resourceData);
+ assertEquals(TitanOperationStatus.ALREADY_LOCKED, status);
+
+ status = titanDao.releaseElement(resourceData);
+ assertEquals(TitanOperationStatus.OK, status);
+
+ nodeLock = titanDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class);
+ assertTrue(nodeLock.isRight());
+ assertEquals(TitanOperationStatus.NOT_FOUND, nodeLock.right().value());
+ titanDao.deleteNode(resourceData, ResourceMetadataData.class);
+ titanDao.commit();
+
+ }
+
+ @Test
+ public void testReLockElement() throws InterruptedException {
+
+ ResourceMetadataData resourceData = new ResourceMetadataData();
+
+ resourceData.getMetadataDataDefinition().setName("resourceForReLock");
+ resourceData.getMetadataDataDefinition().setVersion("0.1");
+ resourceData.getMetadataDataDefinition().setState("newState");
+ resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "."
+ + resourceData.getMetadataDataDefinition().getVersion());
+
+ Either<ResourceMetadataData, TitanOperationStatus> resource1 = titanDao.createNode(resourceData,
+ ResourceMetadataData.class);
+ assertTrue(resource1.isLeft());
+ titanDao.commit();
+ String lockId = "lock_" + resourceData.getLabel() + "_" + resource1.left().value().getUniqueId();
+
+ Either<GraphNodeLock, TitanOperationStatus> nodeLock = titanDao
+ .getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class);
+ assertTrue(nodeLock.isRight());
+ assertEquals(TitanOperationStatus.NOT_FOUND, nodeLock.right().value());
+
+ // lock
+ TitanOperationStatus status = titanDao.lockElement(resourceData);
+ assertEquals(TitanOperationStatus.OK, status);
+
+ nodeLock = titanDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class);
+ assertTrue(nodeLock.isLeft());
+ assertEquals(lockId, nodeLock.left().value().getUniqueId());
+ long time1 = nodeLock.left().value().getTime();
+
+ titanDao.commit();
+
+ // timeout
+ configurationManager.getConfiguration().setTitanLockTimeout(2L);
+ Thread.sleep(5001);
+
+ // relock
+ status = titanDao.lockElement(resourceData);
+ assertEquals(TitanOperationStatus.OK, status);
+
+ nodeLock = titanDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class);
+ assertTrue(nodeLock.isLeft());
+ assertEquals(lockId, nodeLock.left().value().getUniqueId());
+
+ long time2 = nodeLock.left().value().getTime();
+
+ assertTrue(time2 > time1);
+
+ status = titanDao.releaseElement(resourceData);
+ assertEquals(TitanOperationStatus.OK, status);
+
+ nodeLock = titanDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), lockId, GraphNodeLock.class);
+ assertTrue(nodeLock.isRight());
+ assertEquals(TitanOperationStatus.NOT_FOUND, nodeLock.right().value());
+
+ titanDao.deleteNode(resourceData, ResourceMetadataData.class);
+ titanDao.commit();
+
+ }
+
+ @Test
+ public void testBoolean() {
+ ResourceMetadataData resourceData = new ResourceMetadataData();
+
+ resourceData.getMetadataDataDefinition().setName("resourceForLock");
+ resourceData.getMetadataDataDefinition().setVersion("0.1");
+ resourceData.getMetadataDataDefinition().setState("NOT_CERTIFIED_CHECKOUT");
+ resourceData.getMetadataDataDefinition().setHighestVersion(true);
+ resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "."
+ + resourceData.getMetadataDataDefinition().getVersion());
+
+ Either<ResourceMetadataData, TitanOperationStatus> resource1 = titanDao.createNode(resourceData,
+ ResourceMetadataData.class);
+ assertTrue(resource1.isLeft());
+
+ resourceData = new ResourceMetadataData();
+
+ resourceData.getMetadataDataDefinition().setName("resourceForLock");
+ resourceData.getMetadataDataDefinition().setVersion("0.2");
+ resourceData.getMetadataDataDefinition().setState("NOT_CERTIFIED_CHECKOUT");
+ resourceData.getMetadataDataDefinition().setHighestVersion(false);
+ resourceData.getMetadataDataDefinition().setUniqueId(resourceData.getMetadataDataDefinition().getName() + "."
+ + resourceData.getMetadataDataDefinition().getVersion());
+
+ Either<ResourceMetadataData, TitanOperationStatus> resource2 = titanDao.createNode(resourceData,
+ ResourceMetadataData.class);
+ titanDao.commit();
+
+ Map<String, Object> props = new HashMap<String, Object>();
+
+ props.put(GraphPropertiesDictionary.STATE.getProperty(), "NOT_CERTIFIED_CHECKOUT");
+ props.put("name", "resourceForLock");
+ props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), false);
+
+ // get by criteria. must be 1
+ Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = titanDao
+ .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
+ assertTrue(byCriteria.isLeft());
+
+ titanDao.deleteNode(resource1.left().value(), ResourceMetadataData.class);
+
+ titanDao.deleteNode(resource2.left().value(), ResourceMetadataData.class);
+ titanDao.commit();
+ }
+
+ // @Test
+ public void testStringSearch() {
+ TitanGraph graph;
+
+ BaseConfiguration conf = new BaseConfiguration();
+ conf.setProperty("storage.backend", "inmemory");
+ graph = TitanFactory.open(conf);
+
+ // TitanManagement graphMgt = graph.getManagementSystem();
+ TitanManagement graphMgt = graph.openManagement();
+ PropertyKey propKey = graphMgt.makePropertyKey("string1").dataType(String.class).make();
+ graphMgt.buildIndex("string1", Vertex.class).addKey(propKey).unique().buildCompositeIndex();
+
+ propKey = graphMgt.makePropertyKey("string2").dataType(String.class).make();
+
+ // graphMgt.buildIndex("string2", Vertex.class).addKey(propKey,
+ // Mapping.TEXT.getParameter()).buildMixedIndex("search");
+ graphMgt.buildIndex("string2", Vertex.class).addKey(propKey).unique().buildCompositeIndex();
+ graphMgt.commit();
+
+ // TitanVertex v = graph.addVertex();
+ // v.addProperty("string1", "My new String 1");
+ // v.addProperty("string2", "String11");
+ // graph.commit();
+ //
+ // v = graph.addVertex();
+ // v.addProperty("string1", "my new string 1");
+ // v.addProperty("string2", "string11");
+ // graph.commit();
+ //
+ // System.out.println("First index search - case");
+ //
+ // Iterable<Vertex> vertices = graph.getVertices("string1", "My new
+ // String 1");
+ // Iterator<Vertex> iter = vertices.iterator();
+ // while ( iter.hasNext() ){
+ // Vertex ver = iter.next();
+ // System.out.println(com.tinkerpop.blueprints.util.ElementHelper.getProperties(ver));
+ // }
+ // System.out.println("First index search non case");
+ //
+ // vertices = graph.getVertices("string1", "my new string 1");
+ // iter = vertices.iterator();
+ // while ( iter.hasNext() ){
+ // Vertex ver = iter.next();
+ // System.out.println(com.tinkerpop.blueprints.util.ElementHelper.getProperties(ver));
+ // }
+ // System.out.println("Second index search case");
+ //
+ // vertices = graph.getVertices("string2", "String11");
+ // iter = vertices.iterator();
+ // while ( iter.hasNext() ){
+ // Vertex ver = iter.next();
+ // System.out.println(com.tinkerpop.blueprints.util.ElementHelper.getProperties(ver));
+ // }
+ // System.out.println("second index search non case");
+ //
+ // vertices = graph.getVertices("string2", "string11");
+ // iter = vertices.iterator();
+ // while ( iter.hasNext() ){
+ // Vertex ver = iter.next();
+ // System.out.println(com.tinkerpop.blueprints.util.ElementHelper.getProperties(ver));
+ // }
+ // System.out.println("Query index search case");
+ // vertices = graph.query().has("string1", "My new String
+ // 1").vertices();
+ // iter = vertices.iterator();
+ // while ( iter.hasNext() ){
+ // Vertex ver = iter.next();
+ // System.out.println(com.tinkerpop.blueprints.util.ElementHelper.getProperties(ver));
+ // }
+ // System.out.println("Query index search non case");
+ // vertices = graph.query().has("string1", "my new string
+ // 1").vertices();
+ // iter = vertices.iterator();
+ // while ( iter.hasNext() ){
+ // Vertex ver = iter.next();
+ // System.out.println(com.tinkerpop.blueprints.util.ElementHelper.getProperties(ver));
+ // }
+
+ log.debug("**** predicat index search non case");
+ Iterable<TitanVertex> vertices = graph.query().has("string1", Text.REGEX, "my new string 1").vertices();
+ Iterator<TitanVertex> iter = vertices.iterator();
+ while (iter.hasNext()) {
+ Vertex ver = iter.next();
+ // System.out.println(com.tinkerpop.blueprints.util.ElementHelper.getProperties(ver));
+ log.debug("{}", titanDao.getProperties(ver));
+ }
+
+ }
+
+ @Test
+ public void testDuplicateResultDueToTitanBug() {
+
+ // TitanGraph titanGraph = titanDao.getGraph().left().value();
+ // TitanManagement managementSystem = titanGraph.getManagementSystem();
+
+ // GraphPropertiesDictionary[] properties = {
+ // GraphPropertiesDictionary.IS_ABSTRACT,
+ // GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY,
+ // GraphPropertiesDictionary.POSITION_X,
+ // GraphPropertiesDictionary.ARTIFACT_TIMEOUT };
+ //
+ // for (GraphPropertiesDictionary property : properties) {
+ // if (false ==
+ // managementSystem.containsGraphIndex(property.getProperty())) {
+ // PropertyKey propKey1 =
+ // managementSystem.makePropertyKey(property.getProperty()).dataType(property.getClazz()).make();
+ // managementSystem.buildIndex(property.getProperty(),
+ // Vertex.class).addKey(propKey1).unique().buildCompositeIndex();
+ // }
+ // }
+
+ // managementSystem.commit();
+
+ ResourceMetadataData resourceData1 = new ResourceMetadataData();
+ resourceData1.getMetadataDataDefinition().setUniqueId("A");
+ ((ResourceMetadataDataDefinition) resourceData1.getMetadataDataDefinition()).setAbstract(true);
+ resourceData1.getMetadataDataDefinition().setName("aaaa");
+
+ Either<ResourceMetadataData, TitanOperationStatus> newNode1 = titanDao.createNode(resourceData1,
+ ResourceMetadataData.class);
+ assertTrue(newNode1.isLeft());
+ log.debug("{}", newNode1.left().value());
+ // titanDao.commit();
+
+ Map<String, Object> props = new HashMap<>();
+ props.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), true);
+ Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = titanDao
+ .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
+ assertTrue(byCriteria.isLeft());
+ assertEquals("check one result returned", 1, byCriteria.left().value().size());
+ // titanDao.commit();
+
+ ResourceMetadataData resourceToUpdate = new ResourceMetadataData();
+ ((ResourceMetadataDataDefinition) resourceToUpdate.getMetadataDataDefinition()).setAbstract(false);
+ resourceToUpdate.getMetadataDataDefinition().setUniqueId("A");
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceToUpdate,
+ ResourceMetadataData.class);
+ assertTrue(updateNode.isLeft());
+ // titanDao.commit();
+
+ byCriteria = titanDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
+ assertTrue(byCriteria.isRight());
+ assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND,
+ byCriteria.right().value());
+
+ AdditionalInfoParameterData infoParameterData = new AdditionalInfoParameterData();
+ infoParameterData.getAdditionalInfoParameterDataDefinition().setUniqueId("123");
+ Map<String, String> idToKey = new HashMap<>();
+ idToKey.put("key1", "value1");
+ infoParameterData.setIdToKey(idToKey);
+
+ Either<AdditionalInfoParameterData, TitanOperationStatus> newNode2 = titanDao.createNode(infoParameterData,
+ AdditionalInfoParameterData.class);
+ assertTrue(newNode2.isLeft());
+ log.debug("{}", newNode2.left().value());
+ // titanDao.commit();
+
+ Map<String, String> idToKey2 = new HashMap<>();
+ idToKey2.put("key1", "value2");
+
+ Map<String, Object> props2 = new HashMap<>();
+ props2.put(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), "123");
+ Gson gson = new Gson();
+ props2.put(GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY.getProperty(), gson.toJson(idToKey2));
+ // props2.put(GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY.getProperty(),
+ // idToKey2);
+
+ Either<List<AdditionalInfoParameterData>, TitanOperationStatus> byCriteria2 = titanDao
+ .getByCriteria(NodeTypeEnum.AdditionalInfoParameters, props2, AdditionalInfoParameterData.class);
+ assertTrue(byCriteria2.isRight());
+ assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND,
+ byCriteria2.right().value());
+
+ infoParameterData.setIdToKey(idToKey2);
+
+ Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode2 = titanDao.updateNode(infoParameterData,
+ AdditionalInfoParameterData.class);
+ assertTrue(updateNode2.isLeft());
+ // titanDao.commit();
+
+ props2.put(GraphPropertiesDictionary.ADDITIONAL_INFO_ID_TO_KEY.getProperty(), idToKey);
+ byCriteria2 = titanDao.getByCriteria(NodeTypeEnum.AdditionalInfoParameters, props2,
+ AdditionalInfoParameterData.class);
+ assertTrue(byCriteria2.isRight());
+ assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND,
+ byCriteria2.right().value());
+
+ ComponentInstanceData resourceInstanceData = new ComponentInstanceData();
+ resourceInstanceData.getComponentInstDataDefinition().setUniqueId("ri123");
+ resourceInstanceData.getComponentInstDataDefinition().setPosX("22");
+ resourceInstanceData.getComponentInstDataDefinition().setName("myresource_1");
+
+ Either<ComponentInstanceData, TitanOperationStatus> newNode3 = titanDao.createNode(resourceInstanceData,
+ ComponentInstanceData.class);
+ assertTrue(newNode3.isLeft());
+ log.debug("{}", newNode3.left().value());
+ // titanDao.commit();
+
+ resourceInstanceData.getComponentInstDataDefinition().setPosX("50");
+ Either<ComponentInstanceData, TitanOperationStatus> updateNode3 = titanDao.updateNode(resourceInstanceData,
+ ComponentInstanceData.class);
+ assertTrue(updateNode3.isLeft());
+ // titanDao.commit();
+
+ resourceInstanceData.getComponentInstDataDefinition().setName("myresource_2");
+ updateNode3 = titanDao.updateNode(resourceInstanceData, ComponentInstanceData.class);
+ assertTrue(updateNode3.isLeft());
+ // titanDao.commit();
+
+ Map<String, Object> props3 = new HashMap<>();
+ props3.put("positionX", "22");
+ Either<List<ComponentInstanceData>, TitanOperationStatus> byCriteria3 = titanDao
+ .getByCriteria(NodeTypeEnum.ResourceInstance, props3, ComponentInstanceData.class);
+ assertTrue(byCriteria3.isRight());
+ assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND,
+ byCriteria3.right().value());
+
+ props3.put("positionX", "50");
+ byCriteria3 = titanDao.getByCriteria(NodeTypeEnum.ResourceInstance, props3, ComponentInstanceData.class);
+ assertTrue(byCriteria3.isLeft());
+
+ /////////////////////////// check integer ////////////////////////
+
+ ArtifactData artifactData = new ArtifactData();
+ artifactData.getArtifactDataDefinition().setUniqueId("ad234");
+ artifactData.getArtifactDataDefinition().setTimeout(100);
+
+ Either<ArtifactData, TitanOperationStatus> newNode4 = titanDao.createNode(artifactData, ArtifactData.class);
+ assertTrue(newNode4.isLeft());
+ log.debug("{}", newNode4.left().value());
+ // titanDao.commit();
+
+ artifactData.getArtifactDataDefinition().setTimeout(50);
+ Either<ArtifactData, TitanOperationStatus> updateNode4 = titanDao.updateNode(artifactData, ArtifactData.class);
+ assertTrue(updateNode4.isLeft());
+ // titanDao.commit();
+
+ Map<String, Object> props4 = new HashMap<>();
+ props4.put("timeout", 100);
+ Either<List<ArtifactData>, TitanOperationStatus> byCriteria4 = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef,
+ props4, ArtifactData.class);
+ assertTrue(byCriteria4.isRight());
+ assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND,
+ byCriteria4.right().value());
+
+ props4.put("timeout", 50);
+ byCriteria4 = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, props4, ArtifactData.class);
+ assertTrue(byCriteria4.isLeft());
+
+ titanDao.rollback();
+ }
+
+ @Test
+ public void testDuplicateResultUSeHasNotQueryDueToTitanBug() {
+
+ String name = "bbbb";
+
+ ResourceMetadataData resourceData1 = new ResourceMetadataData();
+ resourceData1.getMetadataDataDefinition().setUniqueId("A");
+ ((ResourceMetadataDataDefinition) resourceData1.getMetadataDataDefinition()).setAbstract(true);
+ resourceData1.getMetadataDataDefinition().setName(name);
+
+ Either<ResourceMetadataData, TitanOperationStatus> newNode1 = titanDao.createNode(resourceData1,
+ ResourceMetadataData.class);
+ assertTrue(newNode1.isLeft());
+ log.debug("{}", newNode1.left().value());
+ // titanDao.commit();
+
+ Map<String, Object> props = new HashMap<>();
+ props.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), true);
+ Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = titanDao
+ .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
+ assertTrue(byCriteria.isLeft());
+ assertEquals("check one result returned", 1, byCriteria.left().value().size());
+ // titanDao.commit();
+
+ ResourceMetadataData resourceToUpdate = new ResourceMetadataData();
+ ((ResourceMetadataDataDefinition) resourceToUpdate.getMetadataDataDefinition()).setAbstract(false);
+ resourceToUpdate.getMetadataDataDefinition().setUniqueId("A");
+ Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceToUpdate,
+ ResourceMetadataData.class);
+ assertTrue(updateNode.isLeft());
+ // titanDao.commit();
+
+ // no result where isAbstract = true
+ byCriteria = titanDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
+ assertTrue(byCriteria.isRight());
+ assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND,
+ byCriteria.right().value());
+
+ // one result where isAbstract != true
+ byCriteria = titanDao.getByCriteria(NodeTypeEnum.Resource, null, props, ResourceMetadataData.class);
+ assertTrue(byCriteria.isLeft());
+ assertEquals("check one result returned", 1, byCriteria.left().value().size());
+
+ props.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), false);
+ byCriteria = titanDao.getByCriteria(NodeTypeEnum.Resource, null, props, ResourceMetadataData.class);
+ assertTrue(byCriteria.isRight());
+ assertEquals("check one result returned due to titan bug", TitanOperationStatus.NOT_FOUND,
+ byCriteria.right().value());
+
+ titanDao.rollback();
+
+ }
+
+}
diff --git a/catalog-dao/src/test/resources/application-context-test.xml b/catalog-dao/src/test/resources/application-context-test.xml
new file mode 100644
index 0000000000..468dab3763
--- /dev/null
+++ b/catalog-dao/src/test/resources/application-context-test.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
+ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
+
+ <util:properties id="elasticsearchConfig" location="classpath:elasticsearch.yml" />
+
+
+ <context:component-scan
+ base-package="
+ org.openecomp.sdc.be.dao.impl,
+ org.openecomp.sdc.be.dao.es,
+ org.openecomp.sdc.be.dao.neo4j,
+ org.openecomp.sdc.be.dao.titan,
+ org.openecomp.sdc.be.resources.impl
+ ">
+
+ </context:component-scan>
+
+</beans>
diff --git a/catalog-dao/src/test/resources/cassandra.yaml b/catalog-dao/src/test/resources/cassandra.yaml
new file mode 100644
index 0000000000..39f987152a
--- /dev/null
+++ b/catalog-dao/src/test/resources/cassandra.yaml
@@ -0,0 +1,801 @@
+# Cassandra storage config YAML
+
+# NOTE:
+# See http://wiki.apache.org/cassandra/StorageConfiguration for
+# full explanations of configuration directives
+# /NOTE
+
+# The name of the cluster. This is mainly used to prevent machines in
+# one logical cluster from joining another.
+cluster_name: 'Test Cluster'
+
+# This defines the number of tokens randomly assigned to this node on the ring
+# The more tokens, relative to other nodes, the larger the proportion of data
+# that this node will store. You probably want all nodes to have the same number
+# of tokens assuming they have equal hardware capability.
+#
+# If you leave this unspecified, Cassandra will use the default of 1 token for legacy compatibility,
+# and will use the initial_token as described below.
+#
+# Specifying initial_token will override this setting on the node's initial start,
+# on subsequent starts, this setting will apply even if initial token is set.
+#
+# If you already have a cluster with 1 token per node, and wish to migrate to
+# multiple tokens per node, see http://wiki.apache.org/cassandra/Operations
+num_tokens: 256
+
+# initial_token allows you to specify tokens manually. While you can use # it with
+# vnodes (num_tokens > 1, above) -- in which case you should provide a
+# comma-separated list -- it's primarily used when adding nodes # to legacy clusters
+# that do not have vnodes enabled.
+# initial_token:
+
+# See http://wiki.apache.org/cassandra/HintedHandoff
+# May either be "true" or "false" to enable globally, or contain a list
+# of data centers to enable per-datacenter.
+# hinted_handoff_enabled: DC1,DC2
+hinted_handoff_enabled: true
+# this defines the maximum amount of time a dead host will have hints
+# generated. After it has been dead this long, new hints for it will not be
+# created until it has been seen alive and gone down again.
+max_hint_window_in_ms: 10800000 # 3 hours
+# Maximum throttle in KBs per second, per delivery thread. This will be
+# reduced proportionally to the number of nodes in the cluster. (If there
+# are two nodes in the cluster, each delivery thread will use the maximum
+# rate; if there are three, each will throttle to half of the maximum,
+# since we expect two nodes to be delivering hints simultaneously.)
+hinted_handoff_throttle_in_kb: 1024
+# Number of threads with which to deliver hints;
+# Consider increasing this number when you have multi-dc deployments, since
+# cross-dc handoff tends to be slower
+max_hints_delivery_threads: 2
+
+# Maximum throttle in KBs per second, total. This will be
+# reduced proportionally to the number of nodes in the cluster.
+batchlog_replay_throttle_in_kb: 1024
+
+# Authentication backend, implementing IAuthenticator; used to identify users
+# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthenticator,
+# PasswordAuthenticator}.
+#
+# - AllowAllAuthenticator performs no checks - set it to disable authentication.
+# - PasswordAuthenticator relies on username/password pairs to authenticate
+# users. It keeps usernames and hashed passwords in system_auth.credentials table.
+# Please increase system_auth keyspace replication factor if you use this authenticator.
+authenticator: AllowAllAuthenticator
+
+# Authorization backend, implementing IAuthorizer; used to limit access/provide permissions
+# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthorizer,
+# CassandraAuthorizer}.
+#
+# - AllowAllAuthorizer allows any action to any user - set it to disable authorization.
+# - CassandraAuthorizer stores permissions in system_auth.permissions table. Please
+# increase system_auth keyspace replication factor if you use this authorizer.
+authorizer: AllowAllAuthorizer
+
+# Validity period for permissions cache (fetching permissions can be an
+# expensive operation depending on the authorizer, CassandraAuthorizer is
+# one example). Defaults to 2000, set to 0 to disable.
+# Will be disabled automatically for AllowAllAuthorizer.
+permissions_validity_in_ms: 2000
+
+# Refresh interval for permissions cache (if enabled).
+# After this interval, cache entries become eligible for refresh. Upon next
+# access, an async reload is scheduled and the old value returned until it
+# completes. If permissions_validity_in_ms is non-zero, then this must be
+# also.
+# Defaults to the same value as permissions_validity_in_ms.
+# permissions_update_interval_in_ms: 1000
+
+# The partitioner is responsible for distributing groups of rows (by
+# partition key) across nodes in the cluster. You should leave this
+# alone for new clusters. The partitioner can NOT be changed without
+# reloading all data, so when upgrading you should set this to the
+# same partitioner you were already using.
+#
+# Besides Murmur3Partitioner, partitioners included for backwards
+# compatibility include RandomPartitioner, ByteOrderedPartitioner, and
+# OrderPreservingPartitioner.
+#
+partitioner: org.apache.cassandra.dht.Murmur3Partitioner
+
+# Directories where Cassandra should store data on disk. Cassandra
+# will spread data evenly across them, subject to the granularity of
+# the configured compaction strategy.
+# If not set, the default directory is $CASSANDRA_HOME/data/data.
+# data_file_directories:
+# - /var/lib/cassandra/data
+
+# commit log. when running on magnetic HDD, this should be a
+# separate spindle than the data directories.
+# If not set, the default directory is $CASSANDRA_HOME/data/commitlog.
+# commitlog_directory: /var/lib/cassandra/commitlog
+
+# policy for data disk failures:
+# die: shut down gossip and Thrift and kill the JVM for any fs errors or
+# single-sstable errors, so the node can be replaced.
+# stop_paranoid: shut down gossip and Thrift even for single-sstable errors.
+# stop: shut down gossip and Thrift, leaving the node effectively dead, but
+# can still be inspected via JMX.
+# best_effort: stop using the failed disk and respond to requests based on
+# remaining available sstables. This means you WILL see obsolete
+# data at CL.ONE!
+# ignore: ignore fatal errors and let requests fail, as in pre-1.2 Cassandra
+disk_failure_policy: stop
+
+# policy for commit disk failures:
+# die: shut down gossip and Thrift and kill the JVM, so the node can be replaced.
+# stop: shut down gossip and Thrift, leaving the node effectively dead, but
+# can still be inspected via JMX.
+# stop_commit: shutdown the commit log, letting writes collect but
+# continuing to service reads, as in pre-2.0.5 Cassandra
+# ignore: ignore fatal errors and let the batches fail
+commit_failure_policy: stop
+
+# Maximum size of the key cache in memory.
+#
+# Each key cache hit saves 1 seek and each row cache hit saves 2 seeks at the
+# minimum, sometimes more. The key cache is fairly tiny for the amount of
+# time it saves, so it's worthwhile to use it at large numbers.
+# The row cache saves even more time, but must contain the entire row,
+# so it is extremely space-intensive. It's best to only use the
+# row cache if you have hot rows or static rows.
+#
+# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.
+#
+# Default value is empty to make it "auto" (min(5% of Heap (in MB), 100MB)). Set to 0 to disable key cache.
+key_cache_size_in_mb:
+
+# Duration in seconds after which Cassandra should
+# save the key cache. Caches are saved to saved_caches_directory as
+# specified in this configuration file.
+#
+# Saved caches greatly improve cold-start speeds, and is relatively cheap in
+# terms of I/O for the key cache. Row cache saving is much more expensive and
+# has limited use.
+#
+# Default is 14400 or 4 hours.
+key_cache_save_period: 14400
+
+# Number of keys from the key cache to save
+# Disabled by default, meaning all keys are going to be saved
+# key_cache_keys_to_save: 100
+
+# Maximum size of the row cache in memory.
+# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.
+#
+# Default value is 0, to disable row caching.
+row_cache_size_in_mb: 0
+
+# Duration in seconds after which Cassandra should
+# save the row cache. Caches are saved to saved_caches_directory as specified
+# in this configuration file.
+#
+# Saved caches greatly improve cold-start speeds, and is relatively cheap in
+# terms of I/O for the key cache. Row cache saving is much more expensive and
+# has limited use.
+#
+# Default is 0 to disable saving the row cache.
+row_cache_save_period: 0
+
+# Number of keys from the row cache to save
+# Disabled by default, meaning all keys are going to be saved
+# row_cache_keys_to_save: 100
+
+# Maximum size of the counter cache in memory.
+#
+# Counter cache helps to reduce counter locks' contention for hot counter cells.
+# In case of RF = 1 a counter cache hit will cause Cassandra to skip the read before
+# write entirely. With RF > 1 a counter cache hit will still help to reduce the duration
+# of the lock hold, helping with hot counter cell updates, but will not allow skipping
+# the read entirely. Only the local (clock, count) tuple of a counter cell is kept
+# in memory, not the whole counter, so it's relatively cheap.
+#
+# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.
+#
+# Default value is empty to make it "auto" (min(2.5% of Heap (in MB), 50MB)). Set to 0 to disable counter cache.
+# NOTE: if you perform counter deletes and rely on low gcgs, you should disable the counter cache.
+counter_cache_size_in_mb:
+
+# Duration in seconds after which Cassandra should
+# save the counter cache (keys only). Caches are saved to saved_caches_directory as
+# specified in this configuration file.
+#
+# Default is 7200 or 2 hours.
+counter_cache_save_period: 7200
+
+# Number of keys from the counter cache to save
+# Disabled by default, meaning all keys are going to be saved
+# counter_cache_keys_to_save: 100
+
+# The off-heap memory allocator. Affects storage engine metadata as
+# well as caches. Experiments show that JEMAlloc saves some memory
+# than the native GCC allocator (i.e., JEMalloc is more
+# fragmentation-resistant).
+#
+# Supported values are: NativeAllocator, JEMallocAllocator
+#
+# If you intend to use JEMallocAllocator you have to install JEMalloc as library and
+# modify cassandra-env.sh as directed in the file.
+#
+# Defaults to NativeAllocator
+# memory_allocator: NativeAllocator
+
+# saved caches
+# If not set, the default directory is $CASSANDRA_HOME/data/saved_caches.
+# saved_caches_directory: /var/lib/cassandra/saved_caches
+
+# commitlog_sync may be either "periodic" or "batch."
+#
+# When in batch mode, Cassandra won't ack writes until the commit log
+# has been fsynced to disk. It will wait
+# commitlog_sync_batch_window_in_ms milliseconds between fsyncs.
+# This window should be kept short because the writer threads will
+# be unable to do extra work while waiting. (You may need to increase
+# concurrent_writes for the same reason.)
+#
+# commitlog_sync: batch
+# commitlog_sync_batch_window_in_ms: 2
+#
+# the other option is "periodic" where writes may be acked immediately
+# and the CommitLog is simply synced every commitlog_sync_period_in_ms
+# milliseconds.
+commitlog_sync: periodic
+commitlog_sync_period_in_ms: 10000
+
+# The size of the individual commitlog file segments. A commitlog
+# segment may be archived, deleted, or recycled once all the data
+# in it (potentially from each columnfamily in the system) has been
+# flushed to sstables.
+#
+# The default size is 32, which is almost always fine, but if you are
+# archiving commitlog segments (see commitlog_archiving.properties),
+# then you probably want a finer granularity of archiving; 8 or 16 MB
+# is reasonable.
+commitlog_segment_size_in_mb: 32
+
+# any class that implements the SeedProvider interface and has a
+# constructor that takes a Map<String, String> of parameters will do.
+seed_provider:
+ # Addresses of hosts that are deemed contact points.
+ # Cassandra nodes use this list of hosts to find each other and learn
+ # the topology of the ring. You must change this if you are running
+ # multiple nodes!
+ - class_name: org.apache.cassandra.locator.SimpleSeedProvider
+ parameters:
+ # seeds is actually a comma-delimited list of addresses.
+ # Ex: "<ip1>,<ip2>,<ip3>"
+ - seeds: "127.0.0.1"
+
+# For workloads with more data than can fit in memory, Cassandra's
+# bottleneck will be reads that need to fetch data from
+# disk. "concurrent_reads" should be set to (16 * number_of_drives) in
+# order to allow the operations to enqueue low enough in the stack
+# that the OS and drives can reorder them. Same applies to
+# "concurrent_counter_writes", since counter writes read the current
+# values before incrementing and writing them back.
+#
+# On the other hand, since writes are almost never IO bound, the ideal
+# number of "concurrent_writes" is dependent on the number of cores in
+# your system; (8 * number_of_cores) is a good rule of thumb.
+concurrent_reads: 32
+concurrent_writes: 32
+concurrent_counter_writes: 32
+
+# Total memory to use for sstable-reading buffers. Defaults to
+# the smaller of 1/4 of heap or 512MB.
+# file_cache_size_in_mb: 512
+
+# Total permitted memory to use for memtables. Cassandra will stop
+# accepting writes when the limit is exceeded until a flush completes,
+# and will trigger a flush based on memtable_cleanup_threshold
+# If omitted, Cassandra will set both to 1/4 the size of the heap.
+# memtable_heap_space_in_mb: 2048
+# memtable_offheap_space_in_mb: 2048
+
+# Ratio of occupied non-flushing memtable size to total permitted size
+# that will trigger a flush of the largest memtable. Lager mct will
+# mean larger flushes and hence less compaction, but also less concurrent
+# flush activity which can make it difficult to keep your disks fed
+# under heavy write load.
+#
+# memtable_cleanup_threshold defaults to 1 / (memtable_flush_writers + 1)
+# memtable_cleanup_threshold: 0.11
+
+# Specify the way Cassandra allocates and manages memtable memory.
+# Options are:
+# heap_buffers: on heap nio buffers
+# offheap_buffers: off heap (direct) nio buffers
+# offheap_objects: native memory, eliminating nio buffer heap overhead
+memtable_allocation_type: heap_buffers
+
+# Total space to use for commitlogs. Since commitlog segments are
+# mmapped, and hence use up address space, the default size is 32
+# on 32-bit JVMs, and 8192 on 64-bit JVMs.
+#
+# If space gets above this value (it will round up to the next nearest
+# segment multiple), Cassandra will flush every dirty CF in the oldest
+# segment and remove it. So a small total commitlog space will tend
+# to cause more flush activity on less-active columnfamilies.
+# commitlog_total_space_in_mb: 8192
+
+# This sets the amount of memtable flush writer threads. These will
+# be blocked by disk io, and each one will hold a memtable in memory
+# while blocked.
+#
+# memtable_flush_writers defaults to the smaller of (number of disks,
+# number of cores), with a minimum of 2 and a maximum of 8.
+#
+# If your data directories are backed by SSD, you should increase this
+# to the number of cores.
+#memtable_flush_writers: 8
+
+# A fixed memory pool size in MB for for SSTable index summaries. If left
+# empty, this will default to 5% of the heap size. If the memory usage of
+# all index summaries exceeds this limit, SSTables with low read rates will
+# shrink their index summaries in order to meet this limit. However, this
+# is a best-effort process. In extreme conditions Cassandra may need to use
+# more than this amount of memory.
+index_summary_capacity_in_mb:
+
+# How frequently index summaries should be resampled. This is done
+# periodically to redistribute memory from the fixed-size pool to sstables
+# proportional their recent read rates. Setting to -1 will disable this
+# process, leaving existing index summaries at their current sampling level.
+index_summary_resize_interval_in_minutes: 60
+
+# Whether to, when doing sequential writing, fsync() at intervals in
+# order to force the operating system to flush the dirty
+# buffers. Enable this to avoid sudden dirty buffer flushing from
+# impacting read latencies. Almost always a good idea on SSDs; not
+# necessarily on platters.
+trickle_fsync: false
+trickle_fsync_interval_in_kb: 10240
+
+# TCP port, for commands and data
+# For security reasons, you should not expose this port to the internet. Firewall it if needed.
+storage_port: 7000
+
+# SSL port, for encrypted communication. Unused unless enabled in
+# encryption_options
+# For security reasons, you should not expose this port to the internet. Firewall it if needed.
+ssl_storage_port: 7001
+
+# Address or interface to bind to and tell other Cassandra nodes to connect to.
+# You _must_ change this if you want multiple nodes to be able to communicate!
+#
+# Set listen_address OR listen_interface, not both. Interfaces must correspond
+# to a single address, IP aliasing is not supported.
+#
+# Leaving it blank leaves it up to InetAddress.getLocalHost(). This
+# will always do the Right Thing _if_ the node is properly configured
+# (hostname, name resolution, etc), and the Right Thing is to use the
+# address associated with the hostname (it might not be).
+#
+# Setting listen_address to 0.0.0.0 is always wrong.
+#
+# If you choose to specify the interface by name and the interface has an ipv4 and an ipv6 address
+# you can specify which should be chosen using listen_interface_prefer_ipv6. If false the first ipv4
+# address will be used. If true the first ipv6 address will be used. Defaults to false preferring
+# ipv4. If there is only one address it will be selected regardless of ipv4/ipv6.
+listen_address: localhost
+# listen_interface: eth0
+# listen_interface_prefer_ipv6: false
+
+# Address to broadcast to other Cassandra nodes
+# Leaving this blank will set it to the same value as listen_address
+# broadcast_address: 1.2.3.4
+
+# Internode authentication backend, implementing IInternodeAuthenticator;
+# used to allow/disallow connections from peer nodes.
+# internode_authenticator: org.apache.cassandra.auth.AllowAllInternodeAuthenticator
+
+# Whether to start the native transport server.
+# Please note that the address on which the native transport is bound is the
+# same as the rpc_address. The port however is different and specified below.
+start_native_transport: true
+# port for the CQL native transport to listen for clients on
+# For security reasons, you should not expose this port to the internet. Firewall it if needed.
+native_transport_port: 9042
+# The maximum threads for handling requests when the native transport is used.
+# This is similar to rpc_max_threads though the default differs slightly (and
+# there is no native_transport_min_threads, idle threads will always be stopped
+# after 30 seconds).
+# native_transport_max_threads: 128
+#
+# The maximum size of allowed frame. Frame (requests) larger than this will
+# be rejected as invalid. The default is 256MB.
+# native_transport_max_frame_size_in_mb: 256
+
+# The maximum number of concurrent client connections.
+# The default is -1, which means unlimited.
+# native_transport_max_concurrent_connections: -1
+
+# The maximum number of concurrent client connections per source ip.
+# The default is -1, which means unlimited.
+# native_transport_max_concurrent_connections_per_ip: -1
+
+# Whether to start the thrift rpc server.
+start_rpc: true
+
+# The address or interface to bind the Thrift RPC service and native transport
+# server to.
+#
+# Set rpc_address OR rpc_interface, not both. Interfaces must correspond
+# to a single address, IP aliasing is not supported.
+#
+# Leaving rpc_address blank has the same effect as on listen_address
+# (i.e. it will be based on the configured hostname of the node).
+#
+# Note that unlike listen_address, you can specify 0.0.0.0, but you must also
+# set broadcast_rpc_address to a value other than 0.0.0.0.
+#
+# For security reasons, you should not expose this port to the internet. Firewall it if needed.
+#
+# If you choose to specify the interface by name and the interface has an ipv4 and an ipv6 address
+# you can specify which should be chosen using rpc_interface_prefer_ipv6. If false the first ipv4
+# address will be used. If true the first ipv6 address will be used. Defaults to false preferring
+# ipv4. If there is only one address it will be selected regardless of ipv4/ipv6.
+rpc_address: 0.0.0.0
+# rpc_interface: eth1
+# rpc_interface_prefer_ipv6: false
+
+# port for Thrift to listen for clients on
+rpc_port: 9160
+
+# RPC address to broadcast to drivers and other Cassandra nodes. This cannot
+# be set to 0.0.0.0. If left blank, this will be set to the value of
+# rpc_address. If rpc_address is set to 0.0.0.0, broadcast_rpc_address must
+# be set.
+broadcast_rpc_address: 127.0.0.1
+
+
+
+
+
+
+# enable or disable keepalive on rpc/native connections
+rpc_keepalive: true
+
+# Cassandra provides two out-of-the-box options for the RPC Server:
+#
+# sync -> One thread per thrift connection. For a very large number of clients, memory
+# will be your limiting factor. On a 64 bit JVM, 180KB is the minimum stack size
+# per thread, and that will correspond to your use of virtual memory (but physical memory
+# may be limited depending on use of stack space).
+#
+# hsha -> Stands for "half synchronous, half asynchronous." All thrift clients are handled
+# asynchronously using a small number of threads that does not vary with the amount
+# of thrift clients (and thus scales well to many clients). The rpc requests are still
+# synchronous (one thread per active request). If hsha is selected then it is essential
+# that rpc_max_threads is changed from the default value of unlimited.
+#
+# The default is sync because on Windows hsha is about 30% slower. On Linux,
+# sync/hsha performance is about the same, with hsha of course using less memory.
+#
+# Alternatively, can provide your own RPC server by providing the fully-qualified class name
+# of an o.a.c.t.TServerFactory that can create an instance of it.
+rpc_server_type: sync
+
+# Uncomment rpc_min|max_thread to set request pool size limits.
+#
+# Regardless of your choice of RPC server (see above), the number of maximum requests in the
+# RPC thread pool dictates how many concurrent requests are possible (but if you are using the sync
+# RPC server, it also dictates the number of clients that can be connected at all).
+#
+# The default is unlimited and thus provides no protection against clients overwhelming the server. You are
+# encouraged to set a maximum that makes sense for you in production, but do keep in mind that
+# rpc_max_threads represents the maximum number of client requests this server may execute concurrently.
+#
+# rpc_min_threads: 16
+# rpc_max_threads: 2048
+
+# uncomment to set socket buffer sizes on rpc connections
+# rpc_send_buff_size_in_bytes:
+# rpc_recv_buff_size_in_bytes:
+
+# Uncomment to set socket buffer size for internode communication
+# Note that when setting this, the buffer size is limited by net.core.wmem_max
+# and when not setting it it is defined by net.ipv4.tcp_wmem
+# See:
+# /proc/sys/net/core/wmem_max
+# /proc/sys/net/core/rmem_max
+# /proc/sys/net/ipv4/tcp_wmem
+# /proc/sys/net/ipv4/tcp_wmem
+# and: man tcp
+# internode_send_buff_size_in_bytes:
+# internode_recv_buff_size_in_bytes:
+
+# Frame size for thrift (maximum message length).
+thrift_framed_transport_size_in_mb: 15
+
+# Set to true to have Cassandra create a hard link to each sstable
+# flushed or streamed locally in a backups/ subdirectory of the
+# keyspace data. Removing these links is the operator's
+# responsibility.
+incremental_backups: false
+
+# Whether or not to take a snapshot before each compaction. Be
+# careful using this option, since Cassandra won't clean up the
+# snapshots for you. Mostly useful if you're paranoid when there
+# is a data format change.
+snapshot_before_compaction: false
+
+# Whether or not a snapshot is taken of the data before keyspace truncation
+# or dropping of column families. The STRONGLY advised default of true
+# should be used to provide data safety. If you set this flag to false, you will
+# lose data on truncation or drop.
+auto_snapshot: true
+
+# When executing a scan, within or across a partition, we need to keep the
+# tombstones seen in memory so we can return them to the coordinator, which
+# will use them to make sure other replicas also know about the deleted rows.
+# With workloads that generate a lot of tombstones, this can cause performance
+# problems and even exaust the server heap.
+# (http://www.datastax.com/dev/blog/cassandra-anti-patterns-queues-and-queue-like-datasets)
+# Adjust the thresholds here if you understand the dangers and want to
+# scan more tombstones anyway. These thresholds may also be adjusted at runtime
+# using the StorageService mbean.
+tombstone_warn_threshold: 1000
+tombstone_failure_threshold: 100000
+
+# Granularity of the collation index of rows within a partition.
+# Increase if your rows are large, or if you have a very large
+# number of rows per partition. The competing goals are these:
+# 1) a smaller granularity means more index entries are generated
+# and looking up rows withing the partition by collation column
+# is faster
+# 2) but, Cassandra will keep the collation index in memory for hot
+# rows (as part of the key cache), so a larger granularity means
+# you can cache more hot rows
+column_index_size_in_kb: 64
+
+
+# Log WARN on any batch size exceeding this value. 5kb per batch by default.
+# Caution should be taken on increasing the size of this threshold as it can lead to node instability.
+batch_size_warn_threshold_in_kb: 5
+
+# Number of simultaneous compactions to allow, NOT including
+# validation "compactions" for anti-entropy repair. Simultaneous
+# compactions can help preserve read performance in a mixed read/write
+# workload, by mitigating the tendency of small sstables to accumulate
+# during a single long running compactions. The default is usually
+# fine and if you experience problems with compaction running too
+# slowly or too fast, you should look at
+# compaction_throughput_mb_per_sec first.
+#
+# concurrent_compactors defaults to the smaller of (number of disks,
+# number of cores), with a minimum of 2 and a maximum of 8.
+#
+# If your data directories are backed by SSD, you should increase this
+# to the number of cores.
+#concurrent_compactors: 1
+
+# Throttles compaction to the given total throughput across the entire
+# system. The faster you insert data, the faster you need to compact in
+# order to keep the sstable count down, but in general, setting this to
+# 16 to 32 times the rate you are inserting data is more than sufficient.
+# Setting this to 0 disables throttling. Note that this account for all types
+# of compaction, including validation compaction.
+compaction_throughput_mb_per_sec: 16
+
+# When compacting, the replacement sstable(s) can be opened before they
+# are completely written, and used in place of the prior sstables for
+# any range that has been written. This helps to smoothly transfer reads
+# between the sstables, reducing page cache churn and keeping hot rows hot
+sstable_preemptive_open_interval_in_mb: 50
+
+# Throttles all outbound streaming file transfers on this node to the
+# given total throughput in Mbps. This is necessary because Cassandra does
+# mostly sequential IO when streaming data during bootstrap or repair, which
+# can lead to saturating the network connection and degrading rpc performance.
+# When unset, the default is 200 Mbps or 25 MB/s.
+# stream_throughput_outbound_megabits_per_sec: 200
+
+# Throttles all streaming file transfer between the datacenters,
+# this setting allows users to throttle inter dc stream throughput in addition
+# to throttling all network stream traffic as configured with
+# stream_throughput_outbound_megabits_per_sec
+# inter_dc_stream_throughput_outbound_megabits_per_sec:
+
+# How long the coordinator should wait for read operations to complete
+read_request_timeout_in_ms: 5000
+# How long the coordinator should wait for seq or index scans to complete
+range_request_timeout_in_ms: 10000
+# How long the coordinator should wait for writes to complete
+write_request_timeout_in_ms: 2000
+# How long the coordinator should wait for counter writes to complete
+counter_write_request_timeout_in_ms: 5000
+# How long a coordinator should continue to retry a CAS operation
+# that contends with other proposals for the same row
+cas_contention_timeout_in_ms: 1000
+# How long the coordinator should wait for truncates to complete
+# (This can be much longer, because unless auto_snapshot is disabled
+# we need to flush first so we can snapshot before removing the data.)
+truncate_request_timeout_in_ms: 60000
+# The default timeout for other, miscellaneous operations
+request_timeout_in_ms: 10000
+
+# Enable operation timeout information exchange between nodes to accurately
+# measure request timeouts. If disabled, replicas will assume that requests
+# were forwarded to them instantly by the coordinator, which means that
+# under overload conditions we will waste that much extra time processing
+# already-timed-out requests.
+#
+# Warning: before enabling this property make sure to ntp is installed
+# and the times are synchronized between the nodes.
+cross_node_timeout: false
+
+# Enable socket timeout for streaming operation.
+# When a timeout occurs during streaming, streaming is retried from the start
+# of the current file. This _can_ involve re-streaming an important amount of
+# data, so you should avoid setting the value too low.
+# Default value is 0, which never timeout streams.
+# streaming_socket_timeout_in_ms: 0
+
+# phi value that must be reached for a host to be marked down.
+# most users should never need to adjust this.
+# phi_convict_threshold: 8
+
+# endpoint_snitch -- Set this to a class that implements
+# IEndpointSnitch. The snitch has two functions:
+# - it teaches Cassandra enough about your network topology to route
+# requests efficiently
+# - it allows Cassandra to spread replicas around your cluster to avoid
+# correlated failures. It does this by grouping machines into
+# "datacenters" and "racks." Cassandra will do its best not to have
+# more than one replica on the same "rack" (which may not actually
+# be a physical location)
+#
+# IF YOU CHANGE THE SNITCH AFTER DATA IS INSERTED INTO THE CLUSTER,
+# YOU MUST RUN A FULL REPAIR, SINCE THE SNITCH AFFECTS WHERE REPLICAS
+# ARE PLACED.
+#
+# Out of the box, Cassandra provides
+# - SimpleSnitch:
+# Treats Strategy order as proximity. This can improve cache
+# locality when disabling read repair. Only appropriate for
+# single-datacenter deployments.
+# - GossipingPropertyFileSnitch
+# This should be your go-to snitch for production use. The rack
+# and datacenter for the local node are defined in
+# cassandra-rackdc.properties and propagated to other nodes via
+# gossip. If cassandra-topology.properties exists, it is used as a
+# fallback, allowing migration from the PropertyFileSnitch.
+# - PropertyFileSnitch:
+# Proximity is determined by rack and data center, which are
+# explicitly configured in cassandra-topology.properties.
+# - Ec2Snitch:
+# Appropriate for EC2 deployments in a single Region. Loads Region
+# and Availability Zone information from the EC2 API. The Region is
+# treated as the datacenter, and the Availability Zone as the rack.
+# Only private IPs are used, so this will not work across multiple
+# Regions.
+# - Ec2MultiRegionSnitch:
+# Uses public IPs as broadcast_address to allow cross-region
+# connectivity. (Thus, you should set seed addresses to the public
+# IP as well.) You will need to open the storage_port or
+# ssl_storage_port on the public IP firewall. (For intra-Region
+# traffic, Cassandra will switch to the private IP after
+# establishing a connection.)
+# - RackInferringSnitch:
+# Proximity is determined by rack and data center, which are
+# assumed to correspond to the 3rd and 2nd octet of each node's IP
+# address, respectively. Unless this happens to match your
+# deployment conventions, this is best used as an example of
+# writing a custom Snitch class and is provided in that spirit.
+#
+# You can use a custom Snitch by setting this to the full class name
+# of the snitch, which will be assumed to be on your classpath.
+endpoint_snitch: SimpleSnitch
+
+# controls how often to perform the more expensive part of host score
+# calculation
+dynamic_snitch_update_interval_in_ms: 100
+# controls how often to reset all host scores, allowing a bad host to
+# possibly recover
+dynamic_snitch_reset_interval_in_ms: 600000
+# if set greater than zero and read_repair_chance is < 1.0, this will allow
+# 'pinning' of replicas to hosts in order to increase cache capacity.
+# The badness threshold will control how much worse the pinned host has to be
+# before the dynamic snitch will prefer other replicas over it. This is
+# expressed as a double which represents a percentage. Thus, a value of
+# 0.2 means Cassandra would continue to prefer the static snitch values
+# until the pinned host was 20% worse than the fastest.
+dynamic_snitch_badness_threshold: 0.1
+
+# request_scheduler -- Set this to a class that implements
+# RequestScheduler, which will schedule incoming client requests
+# according to the specific policy. This is useful for multi-tenancy
+# with a single Cassandra cluster.
+# NOTE: This is specifically for requests from the client and does
+# not affect inter node communication.
+# org.apache.cassandra.scheduler.NoScheduler - No scheduling takes place
+# org.apache.cassandra.scheduler.RoundRobinScheduler - Round robin of
+# client requests to a node with a separate queue for each
+# request_scheduler_id. The scheduler is further customized by
+# request_scheduler_options as described below.
+request_scheduler: org.apache.cassandra.scheduler.NoScheduler
+
+# Scheduler Options vary based on the type of scheduler
+# NoScheduler - Has no options
+# RoundRobin
+# - throttle_limit -- The throttle_limit is the number of in-flight
+# requests per client. Requests beyond
+# that limit are queued up until
+# running requests can complete.
+# The value of 80 here is twice the number of
+# concurrent_reads + concurrent_writes.
+# - default_weight -- default_weight is optional and allows for
+# overriding the default which is 1.
+# - weights -- Weights are optional and will default to 1 or the
+# overridden default_weight. The weight translates into how
+# many requests are handled during each turn of the
+# RoundRobin, based on the scheduler id.
+#
+# request_scheduler_options:
+# throttle_limit: 80
+# default_weight: 5
+# weights:
+# Keyspace1: 1
+# Keyspace2: 5
+
+# request_scheduler_id -- An identifier based on which to perform
+# the request scheduling. Currently the only valid option is keyspace.
+# request_scheduler_id: keyspace
+
+# Enable or disable inter-node encryption
+# Default settings are TLS v1, RSA 1024-bit keys (it is imperative that
+# users generate their own keys) TLS_RSA_WITH_AES_128_CBC_SHA as the cipher
+# suite for authentication, key exchange and encryption of the actual data transfers.
+# Use the DHE/ECDHE ciphers if running in FIPS 140 compliant mode.
+# NOTE: No custom encryption options are enabled at the moment
+# The available internode options are : all, none, dc, rack
+#
+# If set to dc cassandra will encrypt the traffic between the DCs
+# If set to rack cassandra will encrypt the traffic between the racks
+#
+# The passwords used in these options must match the passwords used when generating
+# the keystore and truststore. For instructions on generating these files, see:
+# http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore
+#
+server_encryption_options:
+ internode_encryption: none
+ keystore: conf/.keystore
+ keystore_password: cassandra
+ truststore: conf/.truststore
+ truststore_password: cassandra
+ # More advanced defaults below:
+ # protocol: TLS
+ # algorithm: SunX509
+ # store_type: JKS
+ # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]
+ # require_client_auth: false
+
+# enable or disable client/server encryption.
+client_encryption_options:
+ enabled: false
+ keystore: conf/.keystore
+ keystore_password: cassandra
+ # require_client_auth: false
+ # Set trustore and truststore_password if require_client_auth is true
+ # truststore: conf/.truststore
+ # truststore_password: cassandra
+ # More advanced defaults below:
+ # protocol: TLS
+ # algorithm: SunX509
+ # store_type: JKS
+ # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]
+
+# internode_compression controls whether traffic between nodes is
+# compressed.
+# can be: all - all traffic is compressed
+# dc - traffic between different datacenters is compressed
+# none - nothing is compressed.
+internode_compression: all
+
+# Enable or disable tcp_nodelay for inter-dc communication.
+# Disabling it will result in larger (but fewer) network packets being sent,
+# reducing overhead from the TCP protocol itself, at the cost of increasing
+# latency if you block for cross-datacenter responses.
+inter_dc_tcp_nodelay: false
diff --git a/catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml b/catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml
new file mode 100644
index 0000000000..0b43e3b8c6
--- /dev/null
+++ b/catalog-dao/src/test/resources/config/catalog-dao/configuration.yaml
@@ -0,0 +1,120 @@
+identificationHeaderFields:
+ - HTTP_IV_USER
+ - HTTP_CSP_FIRSTNAME
+ - HTTP_CSP_LASTNAME
+ - HTTP_IV_REMOTE_ADDRESS
+ - HTTP_CSP_WSTYPE
+
+
+# catalog backend hostname
+beFqdn: 172.20.43.124:8080
+
+
+# catalog backend http port
+beHttpPort: 8080
+
+# catalog backend http context
+beContext: /sdc/rest/config/get
+
+# catalog backend protocol
+beProtocol: http
+
+# catalog backend ssl port
+beSslPort: 8443
+
+version: 1.0
+released: 2012-11-30
+
+titanCfgFile: src/main/resources/config/titan.properties
+titanInMemoryGraph: true
+titanLockTimeout: 30
+
+# Protocols
+protocols:
+ - http
+ - https
+
+# Users
+users:
+ tom: passwd
+ bob: passwd
+#Neoj4
+neo4j:
+ host: neo4jhost
+ port: 7474
+ user: neo4j
+ password: "12345"
+ maxHttpConnection: 100
+ maxHttpPerRoute: 20
+
+cassandraConfig:
+ cassandraHosts: ['mtanjv9sdcg44']
+ localDataCenter:
+ reconnectTimeout : 30000
+ authenticate: false
+ username: koko
+ password: bobo
+ ssl: false
+ truststorePath : /path/path
+ truststorePassword : 123123
+ keySpaces:
+ - { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+
+#Application-specific settings of ES
+elasticSearch:
+ # Mapping of index prefix to time-based frame. For example, if below is configured:
+ #
+ # - indexPrefix: auditingevents
+ # creationPeriod: minute
+ #
+ # then ES object of type which is mapped to "auditingevents-*" template, and created on 2015-12-23 13:24:54, will enter "auditingevents-2015-12-23-13-24" index.
+ # Another object created on 2015-12-23 13:25:54, will enter "auditingevents-2015-12-23-13-25" index.
+ # If creationPeriod: month, both of the above will enter "auditingevents-2015-12" index.
+ #
+ # Legal values for creationPeriod - year, month, day, hour, minute, none (meaning no time-based behaviour).
+ #
+ # If no creationPeriod is configured for indexPrefix, default behavour is creationPeriod: month.
+
+ indicesTimeFrequency:
+ - indexPrefix: auditingevents
+ creationPeriod: month
+
+switchoverDetector:
+ gBeFqdn: AIO-BE.ecomp.idns.cip
+ gFeFqdn: AIO-FE.ecomp.idns.cip
+ beVip: 1.2.3.4
+ feVip: 1.2.3.4
+ beResolveAttempts: 3
+ feResolveAttempts: 3
+ enabled: false
+ interval: 60
+ changePriorityUser: ecompasdc
+ changePriorityPassword: ecompasdc123
+ publishNetworkUrl: "http://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
+ publishNetworkBody: '{"note":"publish network"}'
+ groups:
+ beSet: { changePriorityUrl: "http://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip?user=root",
+ changePriorityBody: '{"name":"AIO-BE.ecomp.idns.cip","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip","no_ad_redirection":false,"v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_be","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_be"],"failover_policy":["FAILALL"]},"comment":"AIO BE G-fqdn","intended_app_proto":"DNS"}'}
+ feSet: { changePriorityUrl: "http://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip?user=root",
+ changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.cip","v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_fe","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_fe"],"failover_policy":["FAILALL"]},"no_ad_redirection":false,"intended_app_proto":"DNS","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip"}'}
+
+applicationL1Cache:
+ datatypes:
+ enabled: true
+ firstRunDelay: 10
+ pollIntervalInSec: 60
+
+applicationL2Cache:
+ enabled: true
+ catalogL1Cache:
+ enabled: true
+ resourcesSizeInCache: 300
+ servicesSizeInCache: 200
+ productsSizeInCache: 100
+ queue:
+ syncIntervalInSecondes: 60
+ waitOnShutDownInMinutes: 30
+ numberOfCacheWorkers: 4
+toscaValidators:
+ stringMaxLength: 1024 \ No newline at end of file
diff --git a/catalog-dao/src/test/resources/config/catalog-dao/ecomp-error-configuration.yaml b/catalog-dao/src/test/resources/config/catalog-dao/ecomp-error-configuration.yaml
new file mode 100644
index 0000000000..9d7cd74a2b
--- /dev/null
+++ b/catalog-dao/src/test/resources/config/catalog-dao/ecomp-error-configuration.yaml
@@ -0,0 +1,383 @@
+###########################################
+# Note the conventions of the field values:
+# type can be one of: CONFIG_ERROR, SYSTEM_ERROR, DATA_ERROR, CONNECTION_PROBLEM, AUTHENTICATION_PROBLEM
+# severity can be one of: WARN, ERROR, FATAL
+# alarmSeverity can be one of: CRITICAL,MAJOR,MINOR,INFORMATIONAL,NONE
+# code is a unique integer in range of 3003-9999 (3000-3002 are occupied for internal usage)
+# The above enumeration values are out-of-the-box and can be changed in code.
+# In case of config and code mismatch, the appropriate error will be printed to log
+#
+## Range of BE codes - 3010-7999
+
+errors:
+
+ BeRestApiGeneralError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_4000,
+ severity: ERROR,
+ description: "Unexpected error during BE REST API execution",
+ alarmSeverity: CRITICAL
+ }
+
+ BeHealthCheckError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_3010,
+ severity: ERROR,
+ description: "Error during BE Health Check",
+ alarmSeverity: CRITICAL
+ }
+
+ BeInitializationError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_4019,
+ severity: ERROR,
+ description: "Catalog-BE was not initialized properly",
+ alarmSeverity: CRITICAL
+ }
+
+ BeResourceMissingError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_3011,
+ severity: ERROR,
+ description: "Mandatory resource %s cannot be found in repository",
+ alarmSeverity: MAJOR
+ }
+
+ BeServiceMissingError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_3012,
+ severity: ERROR,
+ description: "Mandatory service %s cannot be found in repository",
+ alarmSeverity: MAJOR
+ }
+
+ BeFailedAddingResourceInstanceError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_3013,
+ severity: ERROR,
+ description: "Failed to add resource instance of resource %s to service %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeIncorrectServiceError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_3014,
+ severity: ERROR,
+ description: "Service %s is not valid",
+ alarmSeverity: MAJOR
+ }
+
+ BeRepositoryDeleteError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_3015,
+ severity: ERROR,
+ description: "Failed to delete object %s from repository",
+ alarmSeverity: CRITICAL
+ }
+
+ BeRepositoryQueryError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_3016,
+ severity: ERROR,
+ description: "Failed to fetch from repository %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeInvalidConfigurationError: {
+ type: CONFIG_ERROR,
+ code: ASDC_3017,
+ severity: FATAL,
+ description: "Configuration parameter %s is invalid. Value configured is %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeUebConnectionError: {
+ type: CONNECTION_PROBLEM,
+ code: ASDC_4001,
+ severity: ERROR,
+ description: "Connection problem towards U-EB server. Reason: %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeUebSystemError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_3019,
+ severity: ERROR,
+ description: "Error occured during access to U-EB Server. Operation: %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeUebObjectNotFoundError: {
+ type: DATA_ERROR,
+ code: ASDC_4005,
+ severity: ERROR,
+ description: "Error occured during access to U-EB Server. Data not found: %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeDistributionEngineSystemError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_3021,
+ severity: ERROR,
+ description: "Error occured in Distribution Engine. Failed operation: %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeUebAuthenticationError: {
+ type: AUTHENTICATION_PROBLEM,
+ code: ASDC_4003,
+ severity: ERROR,
+ description: "Authentication problem towards U-EB server. Reason: %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeUebUnkownHostError: {
+ type: CONNECTION_PROBLEM,
+ code: ASDC_4002,
+ severity: ERROR,
+ description: "Connection problem towards U-EB server. Cannot reach host %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeDistributionEngineInvalidArtifactType: {
+ type: DATA_ERROR,
+ code: ASDC_4006,
+ severity: WARN,
+ description: "The artifact type %s does not appear in the list of valid artifacts %s",
+ alarmSeverity: MAJOR
+ }
+ BeInvalidTypeError: {
+ type: DATA_ERROR,
+ code: ASDC_4008,
+ severity: WARN,
+ description: "The type %s of %s is invalid",
+ alarmSeverity: MAJOR
+ }
+ BeInvalidValueError: {
+ type: DATA_ERROR,
+ code: ASDC_3028,
+ severity: WARN,
+ description: "The value %s of %s from type %s is invalid",
+ alarmSeverity: MAJOR
+ }
+
+ BeFailedDeletingResourceInstanceError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_3029,
+ severity: ERROR,
+ description: "Failed to delete resource instance %s from service %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeMissingConfigurationError: {
+ type: CONFIG_ERROR,
+ code: ASDC_3030,
+ severity: FATAL,
+ description: "Configuration parameter %s is missing",
+ alarmSeverity: MAJOR
+ }
+
+ BeConfigurationInvalidListSizeError: {
+ type: CONFIG_ERROR,
+ code: ASDC_3031,
+ severity: FATAL,
+ description: "Configuration parameter %s is invalid. At least %s values shall be configured",
+ alarmSeverity: MAJOR
+ }
+
+ ErrorConfigFileFormat: {
+ type: CONFIG_ERROR,
+ code: ASDC_3032,
+ severity: ERROR,
+ description: "Error element not found in YAML name: %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeMissingArtifactInformationError: {
+ type: DATA_ERROR,
+ code: ASDC_4010,
+ severity: ERROR,
+ description: "Artifact uploaded has missing information. Missing %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeArtifactMissingError: {
+ type: DATA_ERROR,
+ code: ASDC_4011,
+ severity: ERROR,
+ description: "Artifact %s requested is not found",
+ alarmSeverity: MAJOR
+ }
+
+ BeArtifactPayloadInvalid: {
+ type: DATA_ERROR,
+ code: ASDC_4012,
+ severity: ERROR,
+ description: "Payload of artifact uploaded is invalid (invalid MD5 or encryption)",
+ alarmSeverity: MAJOR
+ }
+
+ BeUserMissingError: {
+ type: DATA_ERROR,
+ code: ASDC_4009,
+ severity: ERROR,
+ description: "User %s requested is not found",
+ alarmSeverity: MAJOR
+ }
+
+ BeArtifactInformationInvalidError: {
+ type: DATA_ERROR,
+ code: ASDC_4013,
+ severity: ERROR,
+ description: "Input for artifact metadata is invalid",
+ alarmSeverity: MAJOR
+ }
+ BeFailedAddingCapabilityTypeError: {
+ type: DATA_ERROR,
+ code: ASDC_4015,
+ severity: ERROR,
+ description: "Failed adding capability type",
+ alarmSeverity: CRITICAL
+ }
+
+ BeCapabilityTypeMissingError: {
+ type: DATA_ERROR,
+ code: ASDC_4016,
+ severity: ERROR,
+ description: "Capability Type %s not found",
+ alarmSeverity: CRITICAL
+ }
+
+ BeInterfaceMissingError: {
+ type: DATA_ERROR,
+ code: ASDC_4020,
+ severity: ERROR,
+ description: "Interface %s required is missing",
+ alarmSeverity: MAJOR
+ }
+
+ BeDaoSystemError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_4014,
+ severity: ERROR,
+ description: "Operation towards database failed",
+ alarmSeverity: CRITICAL
+ }
+
+ BeSystemError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_4017,
+ severity: ERROR,
+ description: "Unexpected error during operation",
+ alarmSeverity: CRITICAL
+ }
+
+ BeFailedLockObjectError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_4007,
+ severity: WARN,
+ description: "Failed to lock object for update",
+ alarmSeverity: CRITICAL
+ }
+
+ BeInvalidJsonInput: {
+ type: SYSTEM_ERROR,
+ code: ASDC_4018,
+ severity: ERROR,
+ description: "Failed to convert json input to object",
+ alarmSeverity: MAJOR
+ }
+
+ BeDistributionMissingError: {
+ type: DATA_ERROR,
+ code: ASDC_4021,
+ severity: ERROR,
+ description: "Distribution %s required is missing",
+ alarmSeverity: MAJOR
+ }
+
+ BeHealthCheckRecovery: {
+ type: RECOVERY,
+ code: ASDC_4022,
+ severity: INFO,
+ description: "BE Health Check Recovery",
+ alarmSeverity: INFORMATIONAL
+ }
+ BeFailedCreateNodeError: {
+ type: DATA_ERROR,
+ code: ASDC_6000,
+ severity: ERROR,
+ description: "Failed to create node %s on graph. status is %s",
+ alarmSeverity: MAJOR
+ }
+ BeFailedUpdateNodeError: {
+ type: DATA_ERROR,
+ code: ASDC_6001,
+ severity: ERROR,
+ description: "Failed to update node %s on graph. Status is %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeFailedDeleteNodeError: {
+ type: DATA_ERROR,
+ code: ASDC_6002,
+ severity: ERROR,
+ description: "Failed to delete node %s on graph. Status is %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeFailedRetrieveNodeError: {
+ type: DATA_ERROR,
+ code: ASDC_6003,
+ severity: ERROR,
+ description: "Failed to retrieve node %s from graph. Status is %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeExecuteRollbackError: {
+ type: DATA_ERROR,
+ code: ASDC_6004,
+ severity: ERROR,
+ description: "Going to execute rollback on graph.",
+ alarmSeverity: MAJOR
+ }
+
+ BeFailedFindParentError: {
+ type: DATA_ERROR,
+ code: ASDC_6005,
+ severity: ERROR,
+ description: "Failed to find parent node %s on graph. Status is %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeFailedFindAllNodesError: {
+ type: DATA_ERROR,
+ code: ASDC_6006,
+ severity: ERROR,
+ description: "Failed to fetch all nodes with type %s of parent node %s . Status is %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeFailedFindAssociationError: {
+ type: DATA_ERROR,
+ code: ASDC_6007,
+ severity: ERROR,
+ description: "Cannot find node with type %s associated with node %s . Status is %s",
+ alarmSeverity: MAJOR
+ }
+
+ BeFailedFindAssociationError: {
+ type: DATA_ERROR,
+ code: ASDC_6008,
+ severity: ERROR,
+ description: "Cannot find node with type %s associated with node %s . Status is %s",
+ alarmSeverity: MAJOR
+ }
+ BeComponentCleanerSystemError: {
+ type: SYSTEM_ERROR,
+ code: ASDC_6009,
+ severity: ERROR,
+ description: "Error occured in Component Cleaner Task. Failed operation: %s",
+ alarmSeverity: MAJOR
+ }
+ \ No newline at end of file
diff --git a/catalog-dao/src/test/resources/elasticsearch.yml b/catalog-dao/src/test/resources/elasticsearch.yml
new file mode 100644
index 0000000000..e1808ad7cc
--- /dev/null
+++ b/catalog-dao/src/test/resources/elasticsearch.yml
@@ -0,0 +1,392 @@
+
+elasticSearch.local: true
+elasticSearch.transportclient: false
+cluster.name: elasticsearch_1_5_2222
+
+discovery.zen.ping.multicast.enabled: false
+discovery.zen.ping.unicast.enabled: true
+discovery.zen.ping.unicast.hosts: 1.2.3.4
+transport.client.initial_nodes:
+ - 1.2.3.4:9300
+
+
+#plugin.types: "DeleteByQueryPlugin"
+
+##################### Elasticsearch Configuration Example #####################
+
+# This file contains an overview of various configuration settings,
+# targeted at operations staff. Application developers should
+# consult the guide at <http://elasticsearch.org/guide>.
+#
+# The installation procedure is covered at
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/setup.html>.
+#
+# Elasticsearch comes with reasonable defaults for most settings,
+# so you can try it out without bothering with configuration.
+#
+# Most of the time, these defaults are just fine for running a production
+# cluster. If you're fine-tuning your cluster, or wondering about the
+# effect of certain configuration option, please _do ask_ on the
+# mailing list or IRC channel [http://elasticsearch.org/community].
+
+# Any element in the configuration can be replaced with environment variables
+# by placing them in ${...} notation. For example:
+#
+# node.rack: ${RACK_ENV_VAR}
+
+# For information on supported formats and syntax for the config file, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/setup-configuration.html>
+
+
+################################### Cluster ###################################
+
+# Cluster name identifies your cluster for auto-discovery. If you're running
+# multiple clusters on the same network, make sure you're using unique names.
+#
+# cluster.name: elasticsearch
+
+
+#################################### Node #####################################
+
+# Node names are generated dynamically on startup, so you're relieved
+# from configuring them manually. You can tie this node to a specific name:
+#
+# node.name: "Franz Kafka"
+
+# Every node can be configured to allow or deny being eligible as the master,
+# and to allow or deny to store the data.
+#
+# Allow this node to be eligible as a master node (enabled by default):
+#
+# node.master: true
+#
+# Allow this node to store data (enabled by default):
+#
+# node.data: true
+
+# You can exploit these settings to design advanced cluster topologies.
+#
+# 1. You want this node to never become a master node, only to hold data.
+# This will be the "workhorse" of your cluster.
+#
+# node.master: false
+# node.data: true
+#
+# 2. You want this node to only serve as a master: to not store any data and
+# to have free resources. This will be the "coordinator" of your cluster.
+#
+# node.master: true
+# node.data: false
+#
+# 3. You want this node to be neither master nor data node, but
+# to act as a "search load balancer" (fetching data from nodes,
+# aggregating results, etc.)
+#
+# node.master: false
+# node.data: false
+
+# Use the Cluster Health API [http://localhost:9200/_cluster/health], the
+# Node Info API [http://localhost:9200/_nodes] or GUI tools
+# such as <http://www.elasticsearch.org/overview/marvel/>,
+# <http://github.com/karmi/elasticsearch-paramedic>,
+# <http://github.com/lukas-vlcek/bigdesk> and
+# <http://mobz.github.com/elasticsearch-head> to inspect the cluster state.
+
+# A node can have generic attributes associated with it, which can later be used
+# for customized shard allocation filtering, or allocation awareness. An attribute
+# is a simple key value pair, similar to node.key: value, here is an example:
+#
+# node.rack: rack314
+
+# By default, multiple nodes are allowed to start from the same installation location
+# to disable it, set the following:
+# node.max_local_storage_nodes: 1
+
+
+#################################### Index ####################################
+
+# You can set a number of options (such as shard/replica options, mapping
+# or analyzer definitions, translog settings, ...) for indices globally,
+# in this file.
+#
+# Note, that it makes more sense to configure index settings specifically for
+# a certain index, either when creating it or by using the index templates API.
+#
+# See <http://elasticsearch.org/guide/en/elasticsearch/reference/current/index-modules.html> and
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
+# for more information.
+
+# Set the number of shards (splits) of an index (5 by default):
+#
+# index.number_of_shards: 5
+
+# Set the number of replicas (additional copies) of an index (1 by default):
+#
+# index.number_of_replicas: 1
+
+# Note, that for development on a local machine, with small indices, it usually
+# makes sense to "disable" the distributed features:
+#
+index.number_of_shards: 1
+index.number_of_replicas: 0
+
+# These settings directly affect the performance of index and search operations
+# in your cluster. Assuming you have enough machines to hold shards and
+# replicas, the rule of thumb is:
+#
+# 1. Having more *shards* enhances the _indexing_ performance and allows to
+# _distribute_ a big index across machines.
+# 2. Having more *replicas* enhances the _search_ performance and improves the
+# cluster _availability_.
+#
+# The "number_of_shards" is a one-time setting for an index.
+#
+# The "number_of_replicas" can be increased or decreased anytime,
+# by using the Index Update Settings API.
+#
+# Elasticsearch takes care about load balancing, relocating, gathering the
+# results from nodes, etc. Experiment with different settings to fine-tune
+# your setup.
+
+# Use the Index Status API (<http://localhost:9200/A/_status>) to inspect
+# the index status.
+
+
+#################################### Paths ####################################
+path.home: /src/test/resources
+# Path to directory containing configuration (this file and logging.yml):
+#
+path.conf: /src/test/resources
+
+# Path to directory where to store index data allocated for this node.
+#
+path.data: target/esdata
+#
+# Can optionally include more than one location, causing data to be striped across
+# the locations (a la RAID 0) on a file level, favouring locations with most free
+# space on creation. For example:
+#
+# path.data: /path/to/data1,/path/to/data2
+
+# Path to temporary files:
+#
+path.work: /target/eswork
+
+# Path to log files:
+#
+path.logs: /target/eslogs
+
+# Path to where plugins are installed:
+#
+# path.plugins: /path/to/plugins
+
+
+#################################### Plugin ###################################
+
+# If a plugin listed here is not installed for current node, the node will not start.
+#
+# plugin.mandatory: mapper-attachments,lang-groovy
+
+
+################################### Memory ####################################
+
+# Elasticsearch performs poorly when JVM starts swapping: you should ensure that
+# it _never_ swaps.
+#
+# Set this property to true to lock the memory:
+#
+# bootstrap.mlockall: true
+
+# Make sure that the ES_MIN_MEM and ES_MAX_MEM environment variables are set
+# to the same value, and that the machine has enough memory to allocate
+# for Elasticsearch, leaving enough memory for the operating system itself.
+#
+# You should also make sure that the Elasticsearch process is allowed to lock
+# the memory, eg. by using `ulimit -l unlimited`.
+
+
+############################## Network And HTTP ###############################
+
+# Elasticsearch, by default, binds itself to the 0.0.0.0 address, and listens
+# on port [9200-9300] for HTTP traffic and on port [9300-9400] for node-to-node
+# communication. (the range means that if the port is busy, it will automatically
+# try the next port).
+
+# Set the bind address specifically (IPv4 or IPv6):
+#
+# network.bind_host: 192.168.0.1
+
+# Set the address other nodes will use to communicate with this node. If not
+# set, it is automatically derived. It must point to an actual IP address.
+#
+# network.publish_host: 192.168.0.1
+
+# Set both 'bind_host' and 'publish_host':
+#
+# network.host: 192.168.0.1
+
+# Set a custom port for the node to node communication (9300 by default):
+#
+# transport.tcp.port: 9300
+
+# Enable compression for all communication between nodes (disabled by default):
+#
+# transport.tcp.compress: true
+
+# Set a custom port to listen for HTTP traffic:
+#
+# http.port: 9200
+
+# Set a custom allowed content length:
+#
+# http.max_content_length: 100mb
+
+# Disable HTTP completely:
+#
+# http.enabled: false
+
+
+################################### Gateway ###################################
+
+# The gateway allows for persisting the cluster state between full cluster
+# restarts. Every change to the state (such as adding an index) will be stored
+# in the gateway, and when the cluster starts up for the first time,
+# it will read its state from the gateway.
+
+# There are several types of gateway implementations. For more information, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-gateway.html>.
+
+# The default gateway type is the "local" gateway (recommended):
+#
+# gateway.type: local
+
+# Settings below control how and when to start the initial recovery process on
+# a full cluster restart (to reuse as much local data as possible when using shared
+# gateway).
+
+# Allow recovery process after N nodes in a cluster are up:
+#
+gateway.recover_after_nodes: 1
+
+# Set the timeout to initiate the recovery process, once the N nodes
+# from previous setting are up (accepts time value):
+#
+# gateway.recover_after_time: 5m
+
+# Set how many nodes are expected in this cluster. Once these N nodes
+# are up (and recover_after_nodes is met), begin recovery process immediately
+# (without waiting for recover_after_time to expire):
+#
+gateway.expected_nodes: 1
+
+
+############################# Recovery Throttling #############################
+
+# These settings allow to control the process of shards allocation between
+# nodes during initial recovery, replica allocation, rebalancing,
+# or when adding and removing nodes.
+
+# Set the number of concurrent recoveries happening on a node:
+#
+# 1. During the initial recovery
+#
+# cluster.routing.allocation.node_initial_primaries_recoveries: 4
+#
+# 2. During adding/removing nodes, rebalancing, etc
+#
+# cluster.routing.allocation.node_concurrent_recoveries: 2
+
+# Set to throttle throughput when recovering (eg. 100mb, by default 20mb):
+#
+# indices.recovery.max_bytes_per_sec: 20mb
+
+# Set to limit the number of open concurrent streams when
+# recovering a shard from a peer:
+#
+# indices.recovery.concurrent_streams: 5
+
+
+################################## Discovery ##################################
+
+# Discovery infrastructure ensures nodes can be found within a cluster
+# and master node is elected. Multicast discovery is the default.
+
+# Set to ensure a node sees N other master eligible nodes to be considered
+# operational within the cluster. Its recommended to set it to a higher value
+# than 1 when running more than 2 nodes in the cluster.
+#
+# discovery.zen.minimum_master_nodes: 1
+
+# Set the time to wait for ping responses from other nodes when discovering.
+# Set this option to a higher value on a slow or congested network
+# to minimize discovery failures:
+#
+# discovery.zen.ping.timeout: 3s
+
+# For more information, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-discovery-zen.html>
+
+# Unicast discovery allows to explicitly control which nodes will be used
+# to discover the cluster. It can be used when multicast is not present,
+# or to restrict the cluster communication-wise.
+#
+# 1. Disable multicast discovery (enabled by default):
+#
+# discovery.zen.ping.multicast.enabled: false
+#
+# 2. Configure an initial list of master nodes in the cluster
+# to perform discovery when new nodes (master or data) are started:
+#
+# discovery.zen.ping.unicast.hosts: ["host1", "host2:port"]
+
+# EC2 discovery allows to use AWS EC2 API in order to perform discovery.
+#
+# You have to install the cloud-aws plugin for enabling the EC2 discovery.
+#
+# For more information, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-discovery-ec2.html>
+#
+# See <http://elasticsearch.org/tutorials/elasticsearch-on-ec2/>
+# for a step-by-step tutorial.
+
+# GCE discovery allows to use Google Compute Engine API in order to perform discovery.
+#
+# You have to install the cloud-gce plugin for enabling the GCE discovery.
+#
+# For more information, see <https://github.com/elasticsearch/elasticsearch-cloud-gce>.
+
+# Azure discovery allows to use Azure API in order to perform discovery.
+#
+# You have to install the cloud-azure plugin for enabling the Azure discovery.
+#
+# For more information, see <https://github.com/elasticsearch/elasticsearch-cloud-azure>.
+
+################################## Slow Log ##################################
+
+# Shard level query and fetch threshold logging.
+
+#index.search.slowlog.threshold.query.warn: 10s
+#index.search.slowlog.threshold.query.info: 5s
+#index.search.slowlog.threshold.query.debug: 2s
+#index.search.slowlog.threshold.query.trace: 500ms
+
+#index.search.slowlog.threshold.fetch.warn: 1s
+#index.search.slowlog.threshold.fetch.info: 800ms
+#index.search.slowlog.threshold.fetch.debug: 500ms
+#index.search.slowlog.threshold.fetch.trace: 200ms
+
+#index.indexing.slowlog.threshold.index.warn: 10s
+#index.indexing.slowlog.threshold.index.info: 5s
+#index.indexing.slowlog.threshold.index.debug: 2s
+#index.indexing.slowlog.threshold.index.trace: 500ms
+
+################################## GC Logging ################################
+
+#monitor.jvm.gc.young.warn: 1000ms
+#monitor.jvm.gc.young.info: 700ms
+#monitor.jvm.gc.young.debug: 400ms
+
+#monitor.jvm.gc.old.warn: 10s
+#monitor.jvm.gc.old.info: 5s
+#monitor.jvm.gc.old.debug: 2s
+
diff --git a/catalog-dao/src/test/resources/images/apache.png b/catalog-dao/src/test/resources/images/apache.png
new file mode 100644
index 0000000000..8e9f402d90
--- /dev/null
+++ b/catalog-dao/src/test/resources/images/apache.png
Binary files differ
diff --git a/catalog-dao/src/test/resources/log4j.properties b/catalog-dao/src/test/resources/log4j.properties
new file mode 100644
index 0000000000..c18c3daa0e
--- /dev/null
+++ b/catalog-dao/src/test/resources/log4j.properties
@@ -0,0 +1,8 @@
+# Root logger option
+log4j.rootLogger=info, stdout
+
+# Direct log messages to stdout
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.Target=System.out
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
diff --git a/catalog-dao/src/test/resources/logback-test.xml b/catalog-dao/src/test/resources/logback-test.xml
new file mode 100644
index 0000000000..4b7eb955c7
--- /dev/null
+++ b/catalog-dao/src/test/resources/logback-test.xml
@@ -0,0 +1,13 @@
+<!-- only one line, shut up logback ! -->
+<configuration >
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <Pattern>
+ %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
+ </Pattern>
+ </encoder>
+ </appender>
+ <root level="OFF">
+ <appender-ref ref="STDOUT" />
+ </root>
+</configuration>