Sync Integ to Master
[sdc.git] / asdctool / src / main / java / org / openecomp / sdc / asdctool / impl / TitanGraphInitializer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.asdctool.impl;
22
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.Map;
26
27 import org.apache.tinkerpop.gremlin.structure.Edge;
28 import org.apache.tinkerpop.gremlin.structure.Vertex;
29 import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum;
30 import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
31 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
32 import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils;
33 import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
34 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
35 import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
36 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
37 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
38 import org.openecomp.sdc.be.resources.data.UserData;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import com.thinkaurelius.titan.core.PropertyKey;
43 import com.thinkaurelius.titan.core.TitanException;
44 import com.thinkaurelius.titan.core.TitanFactory;
45 import com.thinkaurelius.titan.core.TitanGraph;
46 import com.thinkaurelius.titan.core.TitanGraphQuery;
47 import com.thinkaurelius.titan.core.schema.ConsistencyModifier;
48 import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
49 import com.thinkaurelius.titan.core.schema.TitanManagement;
50
51 public class TitanGraphInitializer {
52
53         private static Logger logger = LoggerFactory.getLogger(TitanGraphInitializer.class.getName());
54         private static TitanGraph graph;
55
56         public static boolean createGraph(String titanCfgFile) {
57                 logger.info("** createGraph with {}", titanCfgFile);
58                 try {
59                         logger.info("createGraph : try to load file {}", titanCfgFile);
60                         graph = TitanFactory.open(titanCfgFile);
61                         if (graph.isClosed()) {
62                                 return false;
63                         }
64
65                 } catch (TitanException e) {
66                         logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e);
67                         return false;
68                 }
69
70                 createIndexesAndDefaults();
71
72                 logger.info("** Titan graph created ");
73
74                 return true;
75         }
76
77         private static boolean isVertexExist(Map<String, Object> properties) {
78                 TitanGraphQuery query = graph.query();
79
80                 if (properties != null && !properties.isEmpty()) {
81                         for (Map.Entry<String, Object> entry : properties.entrySet()) {
82                                 query = query.has(entry.getKey(), entry.getValue());
83                         }
84                 }
85                 Iterable<Vertex> vertecies = query.vertices();
86                 java.util.Iterator<Vertex> iterator = vertecies.iterator();
87                 if (iterator.hasNext()) {
88                         return true;
89                 }
90                 return false;
91         }
92
93         private static void createDefaultAdminUser() {
94                 createUser(getDefaultUserAdmin());
95                 graph.tx().commit();
96
97         }
98
99         private static void createUser(UserData user) {
100                 Map<String, Object> checkedProperties = new HashMap<>();
101                 checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId());
102                 checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName());
103                 Map<String, Object> properties = null;
104                 if (!isVertexExist(checkedProperties)) {
105                         Vertex vertex = graph.addVertex();
106                         vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName());
107                         properties = user.toGraphMap();
108                         for (Map.Entry<String, Object> entry : properties.entrySet()) {
109                                 vertex.property(entry.getKey(), entry.getValue());
110                         }
111                 }
112         }
113
114         private static UserData getDefaultUserAdmin() {
115                 UserData userData = new UserData();
116                 userData.setAction(ActionEnum.Create);
117                 userData.setElementType(GraphElementTypeEnum.Node);
118                 userData.setUserId("jh0003");
119                 userData.setEmail("admin@sdc.com");
120                 userData.setFirstName("Jimmy");
121                 userData.setLastName("Hendrix");
122                 userData.setRole("ADMIN");
123                 userData.setStatus(UserStatusEnum.ACTIVE.name());
124                 userData.setLastLoginTime(0L);
125                 return userData;
126         }
127
128         private static void createVertexIndixes() {
129                 logger.info("** createVertexIndixes started");
130
131                 TitanManagement graphMgt = graph.openManagement();
132                 TitanGraphIndex index = null;
133                 for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) {
134                         PropertyKey propKey = null;
135                         if (!graphMgt.containsPropertyKey(prop.getProperty())) {
136                                 Class<?> clazz = prop.getClazz();
137                                 if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) {
138                                         propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make();
139                                 }
140                         } else {
141                                 propKey = graphMgt.getPropertyKey(prop.getProperty());
142                         }
143                         if (prop.isIndexed()) {
144                                 if (!graphMgt.containsGraphIndex(prop.getProperty())) {
145                                         if (prop.isUnique()) {
146                                                 index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex();
147
148                                                 graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures
149                                                                                                                                                                         // only
150                                                                                                                                                                         // one
151                                                                                                                                                                         // name
152                                                                                                                                                                         // per
153                                                                                                                                                                         // vertex
154                                                 graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures
155                                                                                                                                                                         // name
156                                                                                                                                                                         // uniqueness
157                                                                                                                                                                         // in
158                                                                                                                                                                         // the
159                                                                                                                                                                         // graph
160
161                                         } else {
162                                                 graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex();
163                                         }
164                                 }
165                         }
166                 }
167                 graphMgt.commit();
168                 logger.info("** createVertexIndixes ended");
169
170         }
171
172         private static void createEdgeIndixes() {
173                 logger.info("** createEdgeIndixes started");
174                 TitanManagement graphMgt = graph.openManagement();
175                 for (GraphEdgePropertiesDictionary prop : GraphEdgePropertiesDictionary.values()) {
176                         if (!graphMgt.containsGraphIndex(prop.getProperty())) {
177                                 PropertyKey propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make();
178                                 graphMgt.buildIndex(prop.getProperty(), Edge.class).addKey(propKey).buildCompositeIndex();
179
180                         }
181                 }
182                 graphMgt.commit();
183                 logger.info("** createEdgeIndixes ended");
184         }
185
186         private static void createIndexesAndDefaults() {
187                 createVertexIndixes();
188                 createEdgeIndixes();
189                 createDefaultAdminUser();
190                 createRootCatalogVertex();
191         }
192
193         private static void createRootCatalogVertex() {
194                 Vertex vertex = graph.addVertex();
195                 vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty(), IdBuilderUtils.generateUniqueId());
196                 vertex.property(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName());
197                 graph.tx().commit();
198         }
199 }