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