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