aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-dao/src/main/java
diff options
context:
space:
mode:
Diffstat (limited to 'catalog-dao/src/main/java')
-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
169 files changed, 23625 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();
+ }
+
+}