Removed sysout and replaced with logger
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / dbgen / SchemaGenerator.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 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 package org.onap.aai.dbgen;
21
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.Map;
25 import java.util.Optional;
26 import java.util.Set;
27
28 import org.apache.tinkerpop.gremlin.structure.Vertex;
29 import org.onap.aai.config.SpringContextAware;
30 import org.onap.aai.db.props.AAIProperties;
31 import org.onap.aai.edges.EdgeIngestor;
32 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
33 import org.onap.aai.introspection.Introspector;
34 import org.onap.aai.introspection.Loader;
35 import org.onap.aai.introspection.LoaderFactory;
36 import org.onap.aai.introspection.ModelType;
37 import org.onap.aai.logging.LogFormatTools;
38 import org.onap.aai.schema.enums.PropertyMetadata;
39 import org.onap.aai.edges.EdgeRule;
40 import org.onap.aai.setup.SchemaVersions;
41 import org.onap.aai.util.AAIConfig;
42
43 import com.att.eelf.configuration.EELFLogger;
44 import com.att.eelf.configuration.EELFManager;
45 import com.google.common.collect.Multimap;
46 import org.janusgraph.core.Cardinality;
47 import org.janusgraph.core.Multiplicity;
48 import org.janusgraph.core.PropertyKey;
49 import org.janusgraph.core.JanusGraph;
50 import org.janusgraph.core.schema.JanusGraphManagement;
51
52 public class SchemaGenerator {
53
54         private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(SchemaGenerator.class);
55
56         /**
57          * Load schema into JanusGraph.
58          *
59          * @param graph
60          *            the graph
61          * @param graphMgmt
62          *            the graph mgmt
63          */
64         public static void loadSchemaIntoJanusGraph(final JanusGraph graph, final JanusGraphManagement graphMgmt,
65                         String backend) {
66
67                 try {
68                         AAIConfig.init();
69                 } catch (Exception ex) {
70                         LOGGER.error(" ERROR - Could not run AAIConfig.init(). " + LogFormatTools.getStackTop(ex));
71                         //System.out.println(" ERROR - Could not run AAIConfig.init(). ");
72                         System.exit(1);
73                 }
74
75                 // NOTE - JanusGraph 0.5.3 doesn't keep a list of legal node Labels.
76                 // They are only used when a vertex is actually being created.
77                 // JanusGraph 1.1 will keep track (we think).
78
79                 // Use EdgeRules to make sure edgeLabels are defined in the db. NOTE:
80                 // the multiplicty used here is
81                 // always "MULTI". This is not the same as our internal "Many2Many",
82                 // "One2One", "One2Many" or "Many2One"
83                 // We use the same edge-label for edges between many different types of
84                 // nodes and our internal
85                 // multiplicty definitions depends on which two types of nodes are being
86                 // connected.
87
88                 Multimap<String, EdgeRule> edges = null;
89                 Set<String> labels = new HashSet<>();
90
91                 EdgeIngestor edgeIngestor = SpringContextAware.getBean(EdgeIngestor.class);
92
93                 try {
94                         edges = edgeIngestor.getAllCurrentRules();
95                 } catch (EdgeRuleNotFoundException e) {
96                         LOGGER.error("Unable to find all rules {}", LogFormatTools.getStackTop(e));
97                 }
98
99                 for (EdgeRule rule : edges.values()) {
100                         labels.add(rule.getLabel());
101                 }
102
103                 for (String label : labels) {
104                         if (graphMgmt.containsRelationType(label)) {
105                                 String dmsg = " EdgeLabel  [" + label + "] already existed. ";
106                                 LOGGER.debug(dmsg);
107                         } else {
108                                 String dmsg = "Making EdgeLabel: [" + label + "]";
109                                 LOGGER.debug(dmsg);
110                                 graphMgmt.makeEdgeLabel(label).multiplicity(Multiplicity.valueOf("MULTI")).make();
111                         }
112                 }
113
114                 // ApplicationContext ctx = SpringContextAware.getApplicationContext();
115                 // Loader loader =
116                 // ctx.getBean(LoaderFactory.class).createLoaderForVersion(ModelType.MOXY,
117                 // AAIProperties.LATEST);
118                 LoaderFactory loaderFactory   = SpringContextAware.getBean(LoaderFactory.class);
119                 SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class);
120
121                 Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
122                 // Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY,
123                 // AAIProperties.LATEST);
124                 Map<String, Introspector> objs = loader.getAllObjects();
125                 Map<String, PropertyKey> seenProps = new HashMap<>();
126
127                 for (Introspector obj : objs.values()) {
128                         for (String propName : obj.getProperties()) {
129                                 String dbPropName = propName;
130                                 Optional<String> alias = obj.getPropertyMetadata(propName, PropertyMetadata.DB_ALIAS);
131                                 if (alias.isPresent()) {
132                                         dbPropName = alias.get();
133                                 }
134                                 if (graphMgmt.containsRelationType(dbPropName)) {
135                                         String dmsg = " PropertyKey  [" + dbPropName + "] already existed in the DB. ";
136                                         LOGGER.debug(dmsg);
137                                 } else {
138                                         Class<?> type = obj.getClass(propName);
139                                         Cardinality cardinality = Cardinality.SINGLE;
140                                         boolean process = false;
141                                         if (obj.isListType(propName) && obj.isSimpleGenericType(propName)) {
142                                                 cardinality = Cardinality.SET;
143                                                 type = obj.getGenericTypeClass(propName);
144                                                 process = true;
145                                         } else if (obj.isSimpleType(propName)) {
146                                                 process = true;
147                                         }
148
149                                         if (process) {
150
151                                                 String imsg = "Creating PropertyKey: [" + dbPropName + "], [" + type.getSimpleName() + "], ["
152                                                                 + cardinality + "]";
153                                                 LOGGER.info(imsg);
154                                                 PropertyKey propK;
155                                                 if (!seenProps.containsKey(dbPropName)) {
156                                                         propK = graphMgmt.makePropertyKey(dbPropName).dataType(type).cardinality(cardinality)
157                                                                         .make();
158                                                         seenProps.put(dbPropName, propK);
159                                                 } else {
160                                                         propK = seenProps.get(dbPropName);
161                                                 }
162                                                 if (graphMgmt.containsGraphIndex(dbPropName)) {
163                                                         String dmsg = " Index  [" + dbPropName + "] already existed in the DB. ";
164                                                         LOGGER.debug(dmsg);
165                                                 } else {
166                                                         if (obj.getIndexedProperties().contains(dbPropName)) {
167                                                                 if (obj.getUniqueProperties().contains(dbPropName)) {
168                                                                         imsg = "Add Unique index for PropertyKey: [" + dbPropName + "]";
169                                                                         LOGGER.info(imsg);
170                                                                         graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).unique()
171                                                                                         .buildCompositeIndex();
172                                                                 } else {
173                                                                         imsg = "Add index for PropertyKey: [" + dbPropName + "]";
174                                                                         LOGGER.info(imsg);
175                                                                         graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).buildCompositeIndex();
176                                                                 }
177                                                         } else {
178                                                                 imsg = "No index added for PropertyKey: [" + dbPropName + "]";
179                                                                 LOGGER.info(imsg);
180                                                         }
181                                                 }
182                                         }
183                                 }
184                         }
185                 }
186
187                 String imsg = "-- About to call graphMgmt commit";
188                 LOGGER.info(imsg);
189                 if(backend != null){
190                         LOGGER.info("Successfully loaded the schema to " + backend);
191                 }
192
193                 graphMgmt.commit();
194         }
195
196 }