re base code
[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 com.thinkaurelius.titan.core.*;
24 import com.thinkaurelius.titan.core.schema.ConsistencyModifier;
25 import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
26 import com.thinkaurelius.titan.core.schema.TitanManagement;
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 java.util.ArrayList;
43 import java.util.HashMap;
44 import java.util.Map;
45
46 public class TitanGraphInitializer {
47
48         private static Logger logger = LoggerFactory.getLogger(TitanGraphInitializer.class.getName());
49         private static TitanGraph graph;
50
51         public static boolean createGraph(String titanCfgFile) {
52                 logger.info("** createGraph with {}", titanCfgFile);
53                 try {
54                         logger.info("createGraph : try to load file {}", titanCfgFile);
55                         graph = TitanFactory.open(titanCfgFile);
56                         if (graph.isClosed()) {
57                                 return false;
58                         }
59
60                 } catch (TitanException e) {
61                         logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e);
62                         return false;
63                 }
64
65                 createIndexesAndDefaults();
66
67                 logger.info("** Titan graph created ");
68
69                 return true;
70         }
71
72         private static boolean isVertexExist(Map<String, Object> properties) {
73                 TitanGraphQuery query = graph.query();
74
75                 if (properties != null && !properties.isEmpty()) {
76                         for (Map.Entry<String, Object> entry : properties.entrySet()) {
77                                 query = query.has(entry.getKey(), entry.getValue());
78                         }
79                 }
80                 Iterable<Vertex> vertecies = query.vertices();
81                 java.util.Iterator<Vertex> iterator = vertecies.iterator();
82                 if (iterator.hasNext()) {
83                         return true;
84                 }
85                 return false;
86         }
87
88         private static boolean isVertexNotExist(Map<String, Object> properties) {
89                 return !isVertexExist(properties);
90         }
91
92         private static void createDefaultAdminUser() {
93                 createUser(getDefaultUserAdmin());
94                 graph.tx().commit();
95
96         }
97
98         private static void createUser(UserData user) {
99                 Map<String, Object> checkedProperties = new HashMap<>();
100                 checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId());
101                 checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName());
102                 Map<String, Object> properties = null;
103                 if (!isVertexExist(checkedProperties)) {
104                         Vertex vertex = graph.addVertex();
105                         vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName());
106                         properties = user.toGraphMap();
107                         for (Map.Entry<String, Object> entry : properties.entrySet()) {
108                                 vertex.property(entry.getKey(), entry.getValue());
109                         }
110                 }
111         }
112
113         private static UserData getDefaultUserAdmin() {
114                 UserData userData = new UserData();
115                 userData.setAction(ActionEnum.Create);
116                 userData.setElementType(GraphElementTypeEnum.Node);
117                 userData.setUserId("jh0003");
118                 userData.setEmail("admin@sdc.com");
119                 userData.setFirstName("Jimmy");
120                 userData.setLastName("Hendrix");
121                 userData.setRole("ADMIN");
122                 userData.setStatus(UserStatusEnum.ACTIVE.name());
123                 userData.setLastLoginTime(0L);
124                 return userData;
125         }
126
127         private static void createVertexIndixes() {
128                 logger.info("** createVertexIndixes started");
129
130                 TitanManagement graphMgt = graph.openManagement();
131                 TitanGraphIndex index = null;
132                 for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) {
133                         PropertyKey propKey = null;
134                         if (!graphMgt.containsPropertyKey(prop.getProperty())) {
135                                 Class<?> clazz = prop.getClazz();
136                                 if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) {
137                                         propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make();
138                                 }
139                         } else {
140                                 propKey = graphMgt.getPropertyKey(prop.getProperty());
141                         }
142                         if (prop.isIndexed()) {
143                                 if (!graphMgt.containsGraphIndex(prop.getProperty())) {
144                                         if (prop.isUnique()) {
145                                                 index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex();
146
147                                                 graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures
148                                                                                                                                                                         // only
149                                                                                                                                                                         // one
150                                                                                                                                                                         // name
151                                                                                                                                                                         // per
152                                                                                                                                                                         // vertex
153                                                 graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures
154                                                                                                                                                                         // name
155                                                                                                                                                                         // uniqueness
156                                                                                                                                                                         // in
157                                                                                                                                                                         // the
158                                                                                                                                                                         // graph
159
160                                         } else {
161                                                 graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex();
162                                         }
163                                 }
164                         }
165                 }
166                 graphMgt.commit();
167                 logger.info("** createVertexIndixes ended");
168
169         }
170
171         private static void createEdgeIndixes() {
172                 logger.info("** createEdgeIndixes started");
173                 TitanManagement graphMgt = graph.openManagement();
174                 for (GraphEdgePropertiesDictionary prop : GraphEdgePropertiesDictionary.values()) {
175                         if (!graphMgt.containsGraphIndex(prop.getProperty())) {
176                                 PropertyKey propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make();
177                                 graphMgt.buildIndex(prop.getProperty(), Edge.class).addKey(propKey).buildCompositeIndex();
178
179                         }
180                 }
181                 graphMgt.commit();
182                 logger.info("** createEdgeIndixes ended");
183         }
184
185         private static void createIndexesAndDefaults() {
186                 createVertexIndixes();
187                 createEdgeIndixes();
188                 createDefaultAdminUser();
189                 createRootVertex(VertexTypeEnum.CATALOG_ROOT);
190                 createRootVertex(VertexTypeEnum.ARCHIVE_ROOT);
191         }
192
193         private static void createRootVertex(VertexTypeEnum vertexTypeEnum) {
194                 Map<String, Object> checkedProperties = new HashMap<>();
195                 checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), vertexTypeEnum.getName());
196                 if (isVertexNotExist(checkedProperties)) {
197                         Vertex vertex = graph.addVertex();
198                         vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty(), IdBuilderUtils.generateUniqueId());
199                         vertex.property(GraphPropertyEnum.LABEL.getProperty(), vertexTypeEnum.getName());
200                         graph.tx().commit();
201                 }
202         }
203
204 }