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